Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

Period.between: years, months, days, and total days

Find the calendar period between two dates and read its components. If you need the total number of days, calculate it directly from the dates.

Version: Java SE 21

Syntax

import java.time.LocalDate;
import java.time.Period;
import java.time.temporal.ChronoUnit;

// start and end are LocalDate values.
Period period = Period.between(start, end);
int years = period.getYears();
int months = period.getMonths();
int days = period.getDays();
long totalDays = ChronoUnit.DAYS.between(start, end);

The static method Period.between(start, end) in java.time.Period takes two LocalDate values, which have no time of day or time zone. The start date is included and the end date is excluded. The method finds the complete months and remaining days, then splits the complete months into 12-month years and leftover months.

The methods getYears(), getMonths(), and getDays() return the year, month, and day components respectively, each as an int. In a result from between, the month component does not include months already counted as years, and the day component is only the days left after accounting for complete months. Equal dates give three zero components. If the end date is before the start date, every nonzero component is negative.

For the total number of calendar days, use ChronoUnit.DAYS.between(start, end) from java.time.temporal. It returns a long, excludes the end date, and gives a negative result if the end comes before the start. Do not convert Period components using a fixed number of days per month or year: their lengths vary with the calendar.

Examples

import java.time.LocalDate;
import java.time.Period;
import java.time.temporal.ChronoUnit;

public class PeriodExample {
    public static void main(String[] args) {
        LocalDate start = LocalDate.of(2023, 1, 15);
        LocalDate end = LocalDate.of(2024, 3, 18);
        Period period = Period.between(start, end);
        long totalDays = ChronoUnit.DAYS.between(start, end);

        System.out.println("years=" + period.getYears());
        System.out.println("months=" + period.getMonths());
        System.out.println("days=" + period.getDays());
        System.out.println("totalDays=" + totalDays);
    }
}

Result

years=1
months=2
days=3
totalDays=428

From `2023-01-15` to `2024-03-18`, the period is 1 year, 2 months, and 3 days. So `getDays()` returns `3`, while `ChronoUnit.DAYS.between(start, end)` returns `428`.

Related lessons

  • Java · Lesson 68 · Basic · Version: 2

Sources