We have already seen to calculate the number of Days between two dates prior to Java 8.
Today, we will discuss how to calculate the number of days between two dates in Java 8.
To calculate the days between two dates we can use the DAYS.between() method of java.time.temporal.ChronoUnit.
Syntax of DAYS.between():
long noOfDaysBetween = DAYS.between(startDate, endDate);
// or alternatively
long noOfDaysBetween = startDate.until(endDate, DAYS);
The startDate is Inclusive and endDate is Exclusive in the calculation of noOfDaysBetween
1. Number of Days between two Dates using DAYS.between() method
2. Parsing the Dates and then calculating the days between them
In the above example we are passing the date in desired format, however if you have the date as a String then you can parse the date to convert it into a Java 8 LocalDate. After the parsing, we are calculating the days between similar to the above example.
You can parse a date of any format to the desired format. Refer Java – parse date tutorial for date parsing examples.