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:
In Jodatime:
Answering wrt to the final JDK1.8 version.
There are two amount classes -
Duration
andPeriod
. 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):
The
Duration
between two temporal objects of the same type can be calculated as follows:The
Period
between twoLocalDate
objects can be calculated as follows: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 theDuration
class (javadoc) - e.g.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 ofLocalDate
- e.g.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: