Learn to convert the LocalDateTime to ZonedDateTime, and vice versa using easy-to-understand Java examples.
An instance of LocalDateTime represents a date-time (to nanosecond precision.) without a time-zone in the ISO-8601 calendar system. A LocalDateTime instance represents a point in the local timeline. It cannot represent an instant on the universal timeline without additional information such as an offset or time zone.
A ZonedDateTime instance represents an instant in the universal timeline. It is the combination of date, time and zone information.
1. LocalDateTime -> ZonedDateTime
To convert from LocalDateTime to ZonedDateTime, we must add the zone offset to the local date-time. Whatever the zone information we will add, the constructed object will represent an instant in the universal timeline with the configured offset.
ZonedDateTime = LocalDateTime + ZoneId
LocalDateTime ldt = LocalDateTime.now(); //Local date time
ZoneId zoneId = ZoneId.of( "Asia/Kolkata" ); //Zone information
ZonedDateTime zdtAtAsia = ldt.atZone( zoneId ); //Local time in Asia timezone
ZonedDateTime zdtAtET = zdtAtAsia
.withZoneSameInstant( ZoneId.of( "America/New_York" ) ); //Sama time in ET timezone
Program Output:
2018-07-15T11:27:46.203763100+05:30[Asia/Kolkata] 2018-07-15T01:57:46.203763100-04:00[America/New_York]
2. ZonedDateTime -> LocalDateTime
Use ZonedDateTime.toLocalDateTime()
method to get local datetime without timezone information.
ZonedDateTime zdtAtET = ZonedDateTime.now(ZoneId.of("America/New_York"));
LocalDateTime ldt = zdtAtET.toLocalDateTime();
System.out.println(zdtAtET);
System.out.println(ldt);
Program Output:
2018-07-15T01:59:52.054839900-04:00[America/New_York] 2018-07-15T01:59:52.054839900
Happy Learning !!