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)
...
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.
Interval between two events is known as Duration. For example : A work start at 10 AM and it ends 12 AM.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With