Learn to calculate number of days between two dates in Java 8 using ChronoUnit.DAYS.between()
and LocalDate.until()
methods.
Read More : Calculate business days between two dates
1. ChronoUnit.DAYS.between()
This is the simplest of all solutions. Internally, it is as simple as date1.toEpochDay() - date2.toEpochDay()
. It count the days since year zero till both LocalDate instances and subtract it.
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 } }
Program output.
99
2. LocalDate.until()
This solution is very much similar to 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 } }
Program output.
99
Drop me your questions related to calculating days between two dates in Java.
Happy Learning !!