86. Converting Calendar to LocalDateTime
In Problem 68, you saw that converting a java.util.Date (date) to a LocalTime can be done as follows:
LocalTime lt = date.toInstant().atZone(zoneId).toLocalTime();
In the same manner, we can convert a java.util.Date to a LocalDateTime (here, zoneId was replaced with ZoneId.systemDefault()):
LocalDateTime ldt = date.toInstant().atZone(
ZoneId.systemDefault()).toLocalDateTime();
We also know that we can obtain a java.util.Date from a Calendar via the getTime() method. So, by gluing the pieces of the puzzle together, we obtain the following code:
public static LocalDateTime
toLocalDateTime(Calendar calendar) {
Date date = calendar.getTime();
return date.toInstant().atZone(
ZoneId.systemDefault()).toLocalDateTime();
}
The same result but following a shorter path can be obtained like this:
return LocalDateTime.ofInstant(Instant.ofEpochMilli(
calendar.getTimeInMillis()), ZoneId.systemDefault());
...