rich
rich

Reputation: 19424

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()?

Upvotes: 2

Views: 2225

Answers (2)

VGR
VGR

Reputation: 44414

A LocalDateTime has no timezone. There is no way to compare it to an Instant or ZonedDateTime, which represent exact points in time.

Since your question is about comparing a Date, the easiest way is to compare an Instant with an Instant:

long seconds = ChronoUnit.SECONDS.between(
    new Date().toInstant(),
    Instant.now());

Upvotes: 3

David SN
David SN

Reputation: 3519

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())

Upvotes: 4

Related Questions