There are a plethora of SO questions that deal with calculating the difference between two dates or two times in Java. Many answers point out the problems with the core Java Date classes, and suggest using Jodatime, but AFAIK, there are none that suggest how to do this using jsr310.
So, are there any methods to calculate the difference between two dates or two times in jsr310?
For reference, the following questions handle this issue:
In core Java:
- milliseconds between two datetimes
In Jodatime:
- days betweens two dates
- Interval between two datetimes
Answering wrt to the final JDK1.8 version.
There are two amount classes - Duration
and Period
. Duration is time-based (nanos) and Period is date-based (year/month/day).
The amount of time between two temporal objects of the same type can be easily calculated in one of two ways (I prefer the first):
long days = ChronoUnit.DAYS.between(start, end);
long days = start.until(end, ChronoUnit.DAYS);
The Duration
between two temporal objects of the same type can be calculated as follows:
Duration d = Duration.between(start, end);
The Period
between two LocalDate
objects can be calculated as follows:
Period p = Period.between(start, end);
How to do this depends on what date or datetime classes are being used.
If you are operating in real time (i.e. with time zones etc. so the datetime can be pinpointed to an exact Instant
on the time-line), you can use the Duration
class (javadoc) - e.g.
Duration diff = Duration.between(InstantProvider startInc, InstantProvider endInc);
where an InstantProvider is able
Alternatively, if you are operating in hypothetical time (i.e. without time zones etc.), you can use the Period
class (javadoc) to get the difference between two instances of LocalDate
- e.g.
// diff in days, months and years:
Period diff = Period.between(LocalDate start, LocalDate end);
// diff in days:
Period diff = Period.daysBetween(LocalDate start, LocalDate end);
However, I'm not aware of any convenient methods for getting the difference between two LocalDateTimes or LocalTimes. But... this could be done using Period as follows:
// diff between LocalDateTimes:
public static Period between(LocalDateTime start, LocalDateTime end){
return Period.of(
end.getYear()-start.getYear(),
end.getMonthOfYear().getValue()-start.getMonthOfYear().getValue(),
end.getDayOfMonth()-start.getDayOfMonth(),
end.getHourOfDay()-start.getHourOfDay(),
end.getMinuteOfHour()-start.getMinuteOfHour(),
end.getSecondOfMinute()-start.getSecondOfMinute(),
end.getNanoOfSecond()-start.getNanoOfSecond()
);
}
// diff between LocalTimes:
public static Period between(LocalTime start, LocalTime end){
return Period.of(0, 0, 0,
end.getHourOfDay()-start.getHourOfDay(),
end.getMinuteOfHour()-start.getMinuteOfHour(),
end.getSecondOfMinute()-start.getSecondOfMinute(),
end.getNanoOfSecond()-start.getNanoOfSecond()
);
}