Encodera

Thanks for reading!

Donate to the site — we work hard for you.

How to find the difference between dates

Short answer

ChronoUnit.DAYS.between() returns the number of days between two dates:

void main() {
    var start = LocalDate.of(2026, 1, 1);
    var end = LocalDate.of(2026, 3, 8);
 
    IO.println(ChronoUnit.DAYS.between(start, end));
}

Output:

66

Years, months, days

Period splits the difference into years, months and days:

void main() {
    var period = Period.between(LocalDate.of(2023, 11, 20), LocalDate.of(2026, 3, 8));
 
    IO.println(period);
    IO.println(period.getYears() + " years, " + period.getMonths() + " months, " + period.getDays() + " days");
}

Output:

P2Y3M16D
2 years, 3 months, 16 days

Hours and minutes

For time use Duration:

void main() {
    var start = LocalDateTime.of(2026, 3, 8, 9, 15);
    var end = LocalDateTime.of(2026, 3, 8, 17, 40);
    var duration = Duration.between(start, end);
 
    IO.println(duration);
    IO.println(duration.toHours() + " h " + duration.toMinutesPart() + " min");
}

Output:

PT8H25M
8 h 25 min

Other units

ChronoUnit can count weeks, months and years:

void main() {
    var start = LocalDate.of(2026, 1, 31);
    var end = LocalDate.of(2026, 12, 25);
 
    IO.println(ChronoUnit.WEEKS.between(start, end));
    IO.println(ChronoUnit.MONTHS.between(start, end));
}

Output:

46
10

Common mistake

Taking getDays() from a Period as the total number of days. It is only the remaining days after years and months:

void main() {
    var start = LocalDate.of(2026, 1, 1);
    var end = LocalDate.of(2026, 3, 8);
 
    IO.println(Period.between(start, end).getDays());
    IO.println(ChronoUnit.DAYS.between(start, end));
}

Output:

7
66

Functions used in this recipe

  • ChronoUnit.between() — Counts the whole units (days, months, hours) between two dates or moments.
  • Period — A calendar amount in years, months and days — for example, an age.
  • Duration — An amount of time in seconds and nanoseconds — hours, minutes, seconds.

Thanks for reading!

Donate to the site — we work hard for you.