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.
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 . If you skip the last step, you'd keep the zone.
The LocalDateTime class represents the date-time,often viewed as year-month-day-hour-minute-second and has got no representation of time-zone or offset from UTC/Greenwich.
1. LocalDate. LocalDate is an immutable class that represents Date with default format of yyyy-MM-dd. We can use now() method to get the current date.
ZonedDateTime is an immutable representation of a date-time with a time-zone. This class stores all date and time fields, to a precision of nanoseconds, and a time-zone, with a zone offset used to handle ambiguous local date-times.
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With