Java Years between 2 Instants

Viewed 2540

In Joda, we can calculate years between 2 Datetime using

Years.between(dateTime1, dateTime2);

Is there any easy way to find years between 2 instants using the java.time API instead without much logic?

ChronoUnit.YEARS.between(instant1, instant2)

fails:

Exception in thread "main" java.time.temporal.UnsupportedTemporalTypeException: Unsupported unit: Years
        at java.time.Instant.until(Instant.java:1157)
        at java.time.temporal.ChronoUnit.between(ChronoUnit.java:272)
        ...
1 Answers

The number of years between two instants is considered undefined (apparently - I was surprised by this), but you can easily convert instants into ZonedDateTime and get a useful result:

Instant now = Instant.now();
Instant ago = Instant.ofEpochSecond(1234567890L);

System.out.println(ChronoUnit.YEARS.between(
  ago.atZone(ZoneId.systemDefault()),
  now.atZone(ZoneId.systemDefault())));

Prints:

8

I suspect the reason you can't directly compare instants is because the location of the year boundary depends on the time zone. That means that ZoneId.systemDefault() may not be what you want! ZoneOffset.UTC would be a reasonable choice, otherwise if there's a time zone that's more meaningful in your context (e.g. the time zone of the user who will see the result) you'd want to use that.

Related