rich rich - 1 month ago 16
Java Question

ChronoUnit.between() for a converted java.util.Date

This works (returns 0):

ChronoUnit.SECONDS.between(
LocalDateTime.now(),
LocalDateTime.now());


This fails:

ChronoUnit.SECONDS.between(
ZonedDateTime.ofInstant(new Date().toInstant(), ZoneId.of("UTC"),
LocalDateTime.now());


With this exception:

Exception in thread "main" java.time.DateTimeException: Unable to obtain ZonedDateTime from TemporalAccessor: 2016-10-27T14:05:37.617 of type java.time.LocalDateTime
...
Caused by: java.time.DateTimeException: Unable to obtain ZoneId from TemporalAccessor: 2016-10-27T14:05:37.617 of type java.time.LocalDateTime
at java.time.ZoneId.from(ZoneId.java:466)
at java.time.ZonedDateTime.from(ZonedDateTime.java:553)
... 3 more


Does anyone know how I can use a java.util.Date in a ChronoUnit.between()?

Answer

The documentation of ChronoUnit.between method says:

This calculates the amount in terms of this unit. The start and end points are supplied as temporal objects and must be of compatible types. The implementation will convert the second type to be an instance of the first type before the calculating the amount.

It is trying to convert the LocalDateTime to a ZonedDateTime. LocalDateTime doesn't have the Zone information and causes the error.

If you use a ZonedDateTime as the second parameter it works correctly:

ChronoUnit.SECONDS.between(ZonedDateTime.ofInstant(new Date().toInstant(), ZoneId.of("UTC")), ZonedDateTime.now())