Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)
        ...
like image 990
user1578872 Avatar asked Nov 15 '17 04:11

user1578872


People also ask

How to check year difference in Java?

Once you have the LocalDate, you can use Months. monthsBetween() and Years. yearsBetween() method to calcualte the number of months and years between two dates in Java. LocalDate jamesBirthDay = new LocalDate(1955, 5, 19); LocalDate now = new LocalDate(2015, 7, 30); int monthsBetween = Months.

What is a definite duration of time between two given instants?

Interval between two events is known as Duration. For example : A work start at 10 AM and it ends 12 AM.

How do you add instant days?

Instant plus() method in Java An immutable copy of a instant where a time unit is added to it can be obtained using the plus() method in the Instant class in Java. This method requires two parameters i.e. time to be added to the instant and the unit in which it is to be added.


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.

like image 111
dimo414 Avatar answered Nov 02 '22 22:11

dimo414