7

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)
        ...
Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
user1578872
  • 7,808
  • 29
  • 108
  • 206
  • What type is `Instance1` ? – Tim Biegeleisen Nov 15 '17 at 04:55
  • Just updated. It is java.time.Instant. – user1578872 Nov 15 '17 at 04:56
  • Possible duplicate of [How can I find the number of years between two dates in android?](https://stackoverflow.com/questions/7906301/how-can-i-find-the-number-of-years-between-two-dates-in-android) – Saif Ahmad Nov 15 '17 at 04:56
  • Related: [java.time.Instant.plus(long amountToAdd, TemporalUnit unit) Unsupported unit](https://stackoverflow.com/questions/47232474/java-time-instant-pluslong-amounttoadd-temporalunit-unit-unsupported-unit#comment81426929_47232474). – Ole V.V. Nov 15 '17 at 07:42

1 Answers1

13

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.

dimo414
  • 47,227
  • 18
  • 148
  • 244