This quick code reference tip with explanation first shows how to calculate the difference between two dates represented by two
java.time.LocalDate instances using
java.time.Period class. It then shows how to get the interval between the two
LocalDate instances in hours, days and years using
Java 8 code to find difference between LocalDate instances using java.time.Period
java.time.Periodis a newly introduced class in Java 8.
Periodholds a ‘duration’ or ‘quantity’ of time in Years, months and days.
- An interval or difference of time between two given dates is a duration of time between the two dates.
- To get the duration between 2
LocalDateinstances we will use the
Period.between()method, which has the signature –
static Period between(LocalDate startDateInclusive, LocalDate endDateExclusive)
- The duration of time between two
LocalDateinstances passed to the method is returned as a
Periodinstance itself by the
- The obtained duration’s specific number of days, years and months breakdown can be obtained using
getYears()instance method of
- In the above example, the difference or interval between 12-Jul-2015 and 22-Aug-2016 is obtained via the
Period.between()method which is assigned to
intervalPeriodobject of type
- The obtained
intervalPeriod‘s days, months and years of difference is then printed which is equal to 1 year, 1 month and 10 days.
Java 8 code to find difference between LocalDate instances using java.time.temporal.ChronoUnit
Enum. It provides different enum constants for different time units such as
ChronoUnit.YEARSand so on.
TemporalUnithas a method
between()which has the following signature –
long between(Temporal temporal1Inclusive, Temporal temporal2Exclusive)
Temporal, using the above
TemporalUnitwe can find the difference between two
LocalDateinstances in the desired unit.
- To invoke the correct
between()method implementation of
Temporalwe will access it via the required
ChronoUnitenum constant. For example – For getting the number of days between two dates we will invoke
toDatevariables passed to it.
- Similarly, the
ChronoUnit.YEARS.between()will be used to get the difference between dates in MONTHS and YEARS.
- So, the difference or interval between 12-Jul-2015 and 22-Aug-2016 equals 407 days OR 13 months OR 1 year.
Important Note regarding choosing between Period and ChronoUnit – The days,months and years obtained through ChronoUnit represent the entire difference individually i.e. total numbers of days between the two dates, total number of months and so on.
The Period.between() method, on the other hand, returns the difference together as the number of Years, Months and Days. This implies that, in case of Period, you cannot use any of the days, months or years value individually if you want the exact difference down to the accuracy of the days.