We receive datetime elements relative to the UTC time like 2004-04-12T13:20:00Z
.
And we would like to output the datetime in the local datetime, that is expressed with an offset relative to the UTC time like 2004-04-12T12:20:00-01:00.
We receive datetime elements relative to the UTC time like 2004-04-12T13:20:00Z
.
And we would like to output the datetime in the local datetime, that is expressed with an offset relative to the UTC time like 2004-04-12T12:20:00-01:00.
With the Java 8 date and time classes this is straightforward. Only catch is, we need to go through ZoneDateTime
if we want to pick om the computer’s default time zone, and then on to OffsetDateTime
to get the output format you requested (another option would be formatting the date and time using a specific DateTimeFormatter
; now I am relying on OffsetDateTime.toString()
).
String utcTime = "2004-04-12T13:20:00Z";
OffsetDateTime dateTimeWithOffset = Instant.parse(utcTime).atZone(ZoneId.systemDefault()).toOffsetDateTime();
System.out.println(dateTimeWithOffset);
On my computer the above prints
2004-04-12T14:20+01:00
In the answer and the code I have on purpose avoided the term “local date-time” that you used in the question. This is to avoid confusion with the class LocalDateTime
, which is used for a date and time without any time zone or offset information.
Use ZonedDateTime
from the java 8 API.
ZonedDateTime.ofInstant(Instant.parse("2004-04-12T13:20:00Z"), ZoneId.of("CET"))
it will give you 2004-04-12T15:20+02:00[CET]
Hope the below solution works.
String date_s = "2004-04-12T13:20:00Z";
SimpleDateFormat dt = new SimpleDateFormat("yyyyy-MM-dd'T'HH:mm:ss'Z'");
Date date = dt.parse(date_s);
Calendar cal = Calendar.getInstance(); // creates calendar
cal.setTime(date); // sets calendar time/date
cal.add(Calendar.HOUR, 1); // adds one hour (do any offset that you want here)
String out = dt.format(cal.getTime());
System.out.println(out.substring(1));
Using the Java 8 JDK, you can use the java.time.Instant
class to refer to UTC time. and the folloowing classes for the offset times :
java.time.LocalDate java.time.LocalTime java.time.LocalDateTime
Example :
Instant instant = Instant.now();
LocalDateTime dateTime = LocalDateTime.ofInstant(instant, ZoneId.ofOffset("MyZoneId", ZoneOffset.ofHours(3)));