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()
);
}