Learn to calculate the number of days between two dates in Java using ChronoUnit.DAYS.between()
and LocalDate.until()
methods.
1. ChronoUnit.DAYS.between()
This is the simplest of all solutions. Internally, it is as simple as date1.toEpochDay() - date2.toEpochDay()
. It counts the days since Epoch till both LocalDate instances and subtracts them.
import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
public class DaysBetweenDates
{
public static void main(String[] args)
{
LocalDate date1 = LocalDate.now();
LocalDate date2 = date1.plusDays(99);
long diffInDays = ChronoUnit.DAYS.between(date1, date2);
System.out.println(diffInDays); // 99
}
}
2. LocalDate.until()
This solution is very much similar to the previous one. And internally, it also uses the same technique as above i.e. date1.toEpochDay() - date2.toEpochDay()
.
import java.time.LocalDate; import java.time.temporal.ChronoUnit; public class DaysBetweenDates { public static void main(String[] args) { LocalDate date1 = LocalDate.now(); LocalDate date2 = date1.plusDays(99); long diffInDays = date1.until(date2, ChronoUnit.DAYS); System.out.println(diffInDays); // 99 } }
Drop me your questions related to calculating the number of days between two dates in Java.
Happy Learning !!