java 8 - how to calculate difference between two dates or java.time.LocalDate instances
This quick code reference tip with explanation first shows how to calculate the difference between two dates represented by two
OUTPUT of the above code
Quick explanation of the above code
OUTPUT of the above code
Quick explanation of the above code
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.
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.time.temporal.ChronoUnit class.
Java 8 code to find difference between LocalDate instances using java.time.Period
Code to find difference between LocalDate instances using java.time.Period
package com.javabrahman.java8.time;
import java.time.LocalDate;
import java.time.Month;
import java.time.Period;
public class LocalDateIntervalPeriod {
public static void main(String args[]){
LocalDate dateFrom = LocalDate.of(2015, Month.JULY, 12);
LocalDate dateTo = LocalDate.of(2016, Month.AUGUST, 22);
Period intervalPeriod = Period.between(dateFrom, dateTo);
System.out.println("Difference of days: " + intervalPeriod.getDays());
System.out.println("Difference of months: " + intervalPeriod.getMonths());
System.out.println("Difference of years: " + intervalPeriod.getYears());
}
}
Difference of days: 10 Difference of months: 1 Difference of years: 1
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 thePeriod.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 aPeriodinstance itself by themethod. - The obtained duration's specific number of days, years and months breakdown can be obtained using
getDays(),getMonths()andgetYears()instance method ofPeriod. - 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 tointervalPeriodobject of typePeriod. - The obtained
intervalPeriod's days, months and years of difference is then printed which is equal to 1 year, 1 month and 10 days.
Difference between LocalDate instances using java.time.temporal.ChronoUnit
package com.javabrahman.java8.time;
import java.time.LocalDate;
import java.time.Month;
import java.time.temporal.ChronoUnit;
public class LocalDateIntervalChronoUnit {
public static void main(String args[]){
LocalDate dateFrom = LocalDate.of(2015, Month.JULY, 12);
LocalDate dateTo = LocalDate.of(2016, Month.AUGUST, 22);
long intervalYears = ChronoUnit.YEARS.between(dateFrom, dateTo);
System.out.println("Total number of years between dates: " + intervalYears);
long intervalMonths = ChronoUnit.MONTHS.between(dateFrom, dateTo);
System.out.println("Total number of months between dates: " + intervalMonths);
long intervalDays = ChronoUnit.DAYS.between(dateFrom, dateTo);
System.out.println("Total number of days between dates:" + intervalDays);
}
}
Total number of years between dates: 1 Total number of months between dates: 13 Total number of days between dates:407
java.time.temporal.ChronoUnitis anEnum. It provides different enum constants for different time units such asChronoUnit.DAYS,ChronoUnit.MONTHS,ChronoUnit.YEARSand so on.ChronoUnitimplements thejava.time.temporal.TemporalUnitinterface.TemporalUnithas a methodbetween()which has the following signature -long between(Temporal temporal1Inclusive, Temporal temporal2Exclusive)- As
LocalDateimplementsTemporal, using the abovebetween()method fromTemporalUnitwe can find the difference between twoLocalDateinstances in the desired unit. - To invoke the correct
between()method implementation ofTemporalwe will access it via the requiredChronoUnitenum constant. For example - For getting the number of days between two dates we will invokeChronoUnit.DAYS.between()withfromDateandtoDatevariables passed to it. - Similarly, the
ChronoUnit.MONTHS.between()andChronoUnit.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.
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.
Tutorials on Java 8’s new Date and Time API
Overview of Java 8's new Date and Time APIClick to Read Overview of Java 8's new Date-Time API Working with time zones in Java 8| ZonedDateTime, ZoneId tutorial with examplesClick to Read tutorial on time zone handling in Java 8 How to convert LocalDate to String and String to LocalDateClick to Read tutorial on String to LocalDate conversions How to convert java.util.Date to java.time.LocalDateClick to Read tutorial on java.util.Date to LocalDate conversion Formatting localized dates in Spanish and FrenchClick to Read date formatting in Spanish & French How to get day-of-week for a given dateHow to get day-of-week using java.time.DayOfWeek enumDate Modification using TemporalAdjuster Click to Read Tutorial on TemporalAdjusters
Overview of Java 8's new Date and Time APIClick to Read Overview of Java 8's new Date-Time API Working with time zones in Java 8| ZonedDateTime, ZoneId tutorial with examplesClick to Read tutorial on time zone handling in Java 8 How to convert LocalDate to String and String to LocalDateClick to Read tutorial on String to LocalDate conversions How to convert java.util.Date to java.time.LocalDateClick to Read tutorial on java.util.Date to LocalDate conversion Formatting localized dates in Spanish and FrenchClick to Read date formatting in Spanish & French How to get day-of-week for a given dateHow to get day-of-week using java.time.DayOfWeek enumDate Modification using TemporalAdjuster Click to Read Tutorial on TemporalAdjusters