Java Years from 2 Instants

In Iodine, we can calculate the years between two days of time using

Years.between(dateTime1, dateTime2); 

Is there an easy way to find years between two points using the java.time API, and not without 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) ... 
+5
source share
1 answer

The number of years between two moments is considered undefined (apparently - I was surprised by this), but you can easily convert moments to 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()))); 

Print

 8 

I suspect that the reason you canโ€™t directly compare the moments is because the location of the yearโ€™s border depends on the time zone. This means that ZoneId.systemDefault() may not be what you want! ZoneOffset.UTC would be a smart choice, otherwise if there is a more meaningful time zone in your context (for example, the time zone of the user who sees the result), you should use it.

+7
source

Source: https://habr.com/ru/post/1273376/


All Articles