user1578872
user1578872

Reputation: 9028

Java Years between 2 Instants

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

Upvotes: 9

Views: 3521

Answers (1)

dimo414
dimo414

Reputation: 48824

The number of years between two instants is considered undefined, but you can 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

You can't directly compare instants because the location of the year boundary depends on the time zone. That means that you need to select the correct time zone for your task - ZoneId.systemDefault() may not be what you want! ZoneOffset.UTC would generally 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.

Upvotes: 14

Related Questions