Learn to convert from LocalDate to ZonedDateTime and from ZonedDateTime to LocalDate in Java 8.
As we know, LocalDate represents a calendar date without the time and the zone information. ZonedDateTime instance contains all three information i.e. date, time and zone.
ZonedDateTime = LocalDate + time + timezone
1. LocalDate to ZonedDateTime
To convert a LocalDate
instance to ZonedDateTime
instance, we have two approaches.
1.1. LocalDate -> ZonedDateTime
If we only want to convert a local date in the current timezone to localdate in a different timezone i.e. only want to add zone information, then we can use LocalDate.atStartOfDay(zoneId)
method.
LocalDate localDate = LocalDate.now();
ZonedDateTime zonedDateTime = localDate.atStartOfDay(ZoneId.of("EST5EDT"));
System.out.println(zonedDateTime);
Program output.
2019-04-02T00:00-04:00[EST5EDT]
1.2. LocalDate -> LocalDateTime -> ZonedDateTime
If we want to add both time and timezone information to a localdate, then we need to add both parts one by one to get to ZonedDateTime
instance. We can use the following methods to add the time information to local date.
ZonedDateTime atStartOfDay()
ZonedDateTime atTime(LocalTime time)
ZonedDateTime atTime(int hour, int minutes)
ZonedDateTime atTime(int hour, int minutes, int seconds)
ZonedDateTime atTime(int hour, int minute, int second, int nanoOfSecond)
Then we can use LocalDateTime.atZone(ZoneId)
method to add zone information.
LocalDate localDate = LocalDate.now(); //local date
LocalDateTime localDateTime = localDate.atTime(10, 45, 56); //Add time information
ZoneId zoneId = ZoneId.of("Asia/Kolkata"); // Zone information
ZonedDateTime zdtAtAsia = localDateTime.atZone(zoneId); // add zone information
ZonedDateTime zdtAtET = zdtAtAsia
.withZoneSameInstant(ZoneId.of("America/New_York")); // Same time in ET timezone
System.out.println(zdtAtAsia);
System.out.println(zdtAtET);
Program output.
2019-04-02T10:45:56+05:30[Asia/Kolkata] 2019-04-02T01:15:56-04:00[America/New_York]
2. ZonedDateTime to LocalDate
To convert ZonedDateTime to LocalDate instance, use toLocalDate()
method. It returns a LocalDate
with the same year, month and day as given date-time.
ZonedDateTime zonedDateTime = ZonedDateTime.now();
LocalDate localDate = zonedDateTime.toLocalDate();
System.out.println(localDate);
Program output.
2019-04-02
Happy Learning !!