We have already seen How to find the number of Days between two dates prior to Java 8. In this tutorial we will see 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
Lets see the complete example of how to use this method.
1. Number of Days between two Dates using DAYS.between() method
import java.time.LocalDate; import java.time.Month; import java.time.temporal.ChronoUnit; public class Example { public static void main(String[] args) { //24-May-2017, change this to your desired Start Date LocalDate dateBefore = LocalDate.of(2017, Month.MAY, 24); //29-July-2017, change this to your desired End Date LocalDate dateAfter = LocalDate.of(2017, Month.JULY, 29); long noOfDaysBetween = ChronoUnit.DAYS.between(dateBefore, dateAfter); System.out.println(noOfDaysBetween); } }
Output:
66
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.
import java.time.LocalDate; import java.time.temporal.ChronoUnit; public class Example { public static void main(String[] args) { String dateBeforeString = "2017-05-24"; String dateAfterString = "2017-07-29"; //Parsing the date LocalDate dateBefore = LocalDate.parse(dateBeforeString); LocalDate dateAfter = LocalDate.parse(dateAfterString); //calculating number of days in between long noOfDaysBetween = ChronoUnit.DAYS.between(dateBefore, dateAfter); //displaying the number of days System.out.println(noOfDaysBetween); } }
Output:
66
Leave a Reply