Week 94 — How can one convert a datetime from one timezone to another?
Question of the Week #94
How can one convert a datetime from one timezone to another?
5 Replies
LocalDateTime
s which are used for representing datetimes don't have any information about the timezone of a given datetime. To add timezone information to a LocalDateTime
, the atZone()
method can be used with a ZoneId
argument obtaining a ZonedDateTime
.
ZonedDateTime
is then able to convert from one timezone to another using the withZoneSameInstant
method that also takes a ZoneId
argument which represents the timezone to convert to. After that, it can be converted to a LocalDateTime
using the toLocalDateTime()
method:
📖 Sample answer from dan1st
ZoneId originalZone = ZoneId.of("America/New_York");
ZoneId targetZone = ZoneId.of("Europe/London");
ZonedDateTime originalDateTime = ZonedDateTime.now(originalZone);
ZonedDateTime convertedDateTime = originalDateTime.withZoneSameInstant(targetZone);
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss z");
Submission from coojak5585
I would create or have a created ZonedDateTime with the original timezone,then I’d have to use withZoneSameInstant() & put a ZoneId with the new time zone between its parenthesis . I also would to have to add to the instants that were in and around the original time zone code/lines , adding “In” with the new time zone directly with the “instant” typed after ZoneDateTime for the new line & new time zone code . The line would read ZoneDateTime instantInET . It would be another “instantInET” with system.out.println() to print/display . The last instant used will be before “instant.” together typed in front of “with.ZoneSameInstant “
to look like this after the the equal sign instant.with.ZoneSameInstant(). Within the ZoneSameInstant parentheses there would the typed “ ZoneId.of.(“ET”)); “ with the new time in it
Submission from miamason
To convert time between time zones in Java, use the ZonedDateTime and ZoneId classes from the java.time package:
1.Create a ZonedDateTime object in the source time zone.
2.Use the withZoneSameInstant() method to convert it to the target time zone.
Example:
ZoneId sourceZone = ZoneId.of("America/New_York");
ZoneId targetZone = ZoneId.of("Asia/Kolkata");
ZonedDateTime sourceTime = ZonedDateTime.now(sourceZone);
ZonedDateTime targetTime = sourceTime.withZoneSameInstant(targetZone);
Submission from harshtarsariya