Course contentsShow
← Java
Lesson 1863 of 2,87038. Date and Time API (java.time)Free lesson

Period.between: Computing Date Differences

Calculate the period between two LocalDate objects, accounting for year, month, and day differences.

Period.between: Computing Date Differences

You'll learn how to calculate the exact difference between two dates in terms of years, months, and days using Period.between().

The Core Idea

While Duration measures time-based amounts (hours, minutes, seconds), Period measures date-based amounts (years, months, days). The Period.between() method calculates the difference between two LocalDate objects, giving you a human-readable result like "2 years, 3 months, and 5 days."

Think of it like calculating someone's age: you don't just count total days—you naturally think "25 years and 6 months old," accounting for varying month lengths and leap years.

Using Period.between()

The between() method takes two LocalDate parameters: a start date and an end date. It returns a Period representing the difference:

LocalDate start = LocalDate.of(2020, 1, 15);
LocalDate end = LocalDate.of(2023, 4, 20);

Period period = Period.between(start, end);

System.out.println(period);  // P3Y3M5D (ISO-8601 format)
System.out.println(period.getYears());   // 3
System.out.println(period.getMonths());  // 3
System.out.println(period.getDays());    // 5

Date Order Matters

If the end date is before the start date, you'll get a negative period:

LocalDate start = LocalDate.of(2023, 6, 10);
LocalDate end = LocalDate.of(2023, 3, 5);

Period period = Period.between(start, end);
System.out.println(period.getMonths());  // -3
System.out.println(period.getDays());    // -5

Smart Calendar Math

Period.between() understands calendar complexities—it properly handles varying month lengths and leap years, giving you accurate human-oriented differences rather than raw day counts.

Key Takeaway: Use Period.between() to calculate date-based differences between two LocalDate objects, accounting for years, months, and days in a calendar-aware manner.