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.
source share