Sunday, 23 February 2020

Java 8 | Calculate days between two dates

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

package com.algorithmforum.date;

import java.time.LocalDate;
import java.time.Month;
import java.time.temporal.ChronoUnit;

public class DaysDiffJava8 {
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);

// Logic to calculate the days difference.
long noOfDaysBetween = ChronoUnit.DAYS.between(dateBefore, dateAfter);
System.out.println(noOfDaysBetween);
}
}

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.

package com.algorithmforum.date;

import java.time.LocalDate;
import java.time.temporal.ChronoUnit;

public class DaysDiffJava8 {
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);
}
}