rich rich - 1 year ago 94
Java Question

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

This works (returns 0):


This fails:

ZonedDateTime.ofInstant(new Date().toInstant(), ZoneId.of("UTC"),;

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(
at java.time.ZonedDateTime.from(
... 3 more

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

Answer Source

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")),
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download