Changing LocalDateTime based on time difference in current time zone vs. eastern time zone

yalpsid eman :

Let's say one week ago I generate a LocalDateTime of 2015-10-10T10:00:00. Furthermore, let's assume I generate my current time zone id as such

TimeZone timeZone = TimeZone.getDefault();
String zoneId = timeZone.getId();  // "America/Chicago"

And my zoneId is "America/Chicago".

Is there an easy way I can convert my LocalDateTime to one for the time zone id "America/New_York" (ie so my updated LocalDateTime would be 2015-10-10T11:00:00)?

More importantly, is there a way I can convert my LocalDateTime to eastern time (ie, to a time zone with zoneId "America/New_York") no matter what time zone I am in? I am specifically looking for a way to do this with any LocalDateTime object generated in the past, and not necessarily for the current time this instant.

Andreas :

To convert a LocalDateTime to another time zone, you first apply the original time zone using atZone(), which returns a ZonedDateTime, then convert to the new time zone using withZoneSameInstant(), and finally convert the result back to a LocalDateTime.

LocalDateTime oldDateTime = LocalDateTime.parse("2015-10-10T10:00:00");
ZoneId oldZone = ZoneId.of("America/Chicago");

ZoneId newZone = ZoneId.of("America/New_York");
LocalDateTime newDateTime = oldDateTime.atZone(oldZone)
                                       .withZoneSameInstant(newZone)
                                       .toLocalDateTime();
System.out.println(newDateTime.format(DateTimeFormatter.ISO_LOCAL_DATE_TIME));
2015-10-10T11:00:00

If you skip the last step, you'd keep the zone.

ZonedDateTime newDateTime = oldDateTime.atZone(oldZone)
                                       .withZoneSameInstant(newZone);
System.out.println(newDateTime.format(DateTimeFormatter.ISO_DATE_TIME));
2015-10-10T11:00:00-04:00[America/New_York]

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=455361&siteId=1