Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Java reference

Period

A calendar amount in years, months and days — for example, an age.

Available since: Java 8

Syntax

public final class Period implements ChronoPeriod

Examples

An age from a birth date:

void main() {
    LocalDate birth = LocalDate.of(1990, 8, 25);
    LocalDate today = LocalDate.of(2025, 3, 14);
    Period age = Period.between(birth, today);
    IO.println(age);
    IO.println(age.getYears() + " years, " + age.getMonths() + " months, " + age.getDays() + " days");
}

Output:

P34Y6M17D
34 years, 6 months, 17 days

Adding a period to a date:

void main() {
    Period trial = Period.ofMonths(1).plusDays(14);
    IO.println(trial);
    IO.println(LocalDate.of(2025, 1, 20).plus(trial));
}

Output:

P1M14D
2025-03-06

Notes

getDays() is only the remaining days after full months, not the total number of days. The total number of days between dates is ChronoUnit.DAYS.between(a, b).

See also

  • Duration — An amount of time in seconds and nanoseconds — hours, minutes, seconds.
  • ChronoUnit.between() — Counts the whole units (days, months, hours) between two dates or moments.
  • LocalDate.plusDays() — Returns a date the given number of days later. Related: minusDays(), plusWeeks(), plusMonths(), plusYears().

Related recipes

In the tutorial

  • Dates and times — The java.time package — LocalDate, LocalTime, LocalDateTime, date arithmetic, Period, Duration, ChronoUnit, time zones and Instant.

Thanks for reading!

Donate to the site — we work hard for you.