Calculate Days Between Two Dates in Java
Problem
The difference between two dates can be measured as a single unit (a total number of days) or as a calendar period (months plus leftover days).
Find how many days and whole weeks lie between 15 January 2026 and 11 October 2026.
Java Program
import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
public class DaysBetweenDates {
public static void main(String[] args) {
LocalDate start = LocalDate.of(2026, 1, 15);
LocalDate end = LocalDate.of(2026, 10, 11);
long days = ChronoUnit.DAYS.between(start, end); // end is exclusive
long weeks = ChronoUnit.WEEKS.between(start, end); // whole weeks only
long backwards = ChronoUnit.DAYS.between(end, start);
System.out.println("Days between: " + days);
System.out.println("Whole weeks: " + weeks);
System.out.println("Reversed args: " + backwards);
}
}Output
Core Logic
ChronoUnit.DAYS.between(start, end) counts the days from start up to, but not including, end.
- 1
LocalDate.ofcreates the two fixed dates. - 2
ChronoUnit.DAYS.betweenreturns the total day count as along. - 3
ChronoUnit.WEEKS.betweencounts only complete weeks. - 4Swapping the arguments returns the same distance with a negative sign.
Key Point: The end date is exclusive — DAYS.between(d, d.plusDays(1)) is 1, not 2; add one yourself if you need to count both endpoints, as in hotel or leave calculations.
Key Concepts
Approach 2: Using Period.between()
import java.time.LocalDate;
import java.time.Period;
public class DaysBetweenPeriod {
public static void main(String[] args) {
LocalDate start = LocalDate.of(2026, 1, 15);
LocalDate end = LocalDate.of(2026, 10, 11);
Period gap = Period.between(start, end); // calendar-aware: years, months and leftover days
System.out.println(gap.getMonths() + " months and " + gap.getDays() + " days");
System.out.println("ISO form: " + gap);
}
}
Output
Core Logic
Period expresses the gap the way people describe it — in years, months and leftover days — following the calendar.
- 1
Period.between(start, end)computes the calendar difference. - 2
getMonths()andgetDays()return its parts. - 3
toString()prints the ISO form, such asP8M26D.
Key Point: Period.getDays() is only the leftover days (26), not the total (269) — use ChronoUnit.DAYS when you need the total.
Key Concepts
Interview Questions
Why use ChronoUnit.DAYS.between instead of Period?
ChronoUnit.DAYS.between gives the total number of days. Period splits the gap into years, months and leftover days.
How do you count days including both the start and end?
Add one to the result, because between excludes the end date.