Sub topic 12
Measuring Date-Based Amounts with Period
Sometimes you need an amount of time measured in calendar units: "2 years, 3 months, and 5 days" or "30 days from today." Java gives you the Period class for this. A Period is an amount of time stored as years, months, and days. It is date-based, so it works with LocalDate and other types that have a date part.
This chapter shows how to create a Period, how to measure the Period between two dates, how to add one to a date, and the surprises to watch for.
What a Period Is
A Period holds three separate numbers:
- years
- months
- days
Java does not mix these numbers together. Period.of(0, 14, 0) stays "14 months" and does not turn into "1 year, 2 months" on its own. The reason is that months and years have no fixed length. A month can have 28, 29, 30, or 31 days, so Java keeps each unit separate and only works out the real calendar length when you add the Period to an actual date.
A Period is also immutable, which means it never changes after it is created. Any method that looks like it changes a Period returns a new one instead.
Period Compared with Duration
The previous chapter covered Duration. The table shows how the two differ.
| Feature | Period | Duration |
|---|---|---|
| Units stored | Years, months, days | Seconds and nanoseconds |
| Works with | `LocalDate`, `LocalDateTime`, `ZonedDateTime` | `LocalTime`, `LocalDateTime`, `Instant`, `ZonedDateTime` |
| "1 day" means | One calendar day | Exactly 24 hours |
| Text form | `P1Y2M3D` | `PT2H15M` |
| Typical use | Ages, subscriptions, due dates | Timeouts, stopwatch timing |
Use Period when people would count the amount on a calendar. Use Duration when they would count it on a clock.
Creating a Period
Java gives you several factory methods. A factory method is a static method that builds an object for you.
| Method | Example | Prints |
|---|---|---|
| `Period.of(y, m, d)` | `Period.of(1, 2, 3)` | `P1Y2M3D` |
| `Period.ofYears(n)` | `Period.ofYears(2)` | `P2Y` |
| `Period.ofMonths(n)` | `Period.ofMonths(18)` | `P18M` |
| `Period.ofWeeks(n)` | `Period.ofWeeks(2)` | `P14D` |
| `Period.ofDays(n)` | `Period.ofDays(10)` | `P10D` |
| `Period.parse(text)` | `Period.parse("P1Y2M3D")` | `P1Y2M3D` |
The printed text uses the ISO-8601 format, an international standard for writing dates and times. P means "period," then each number is followed by its unit: Y for years, M for months, D for days. A Period of zero prints as P0D.
import java.time.Period;
public class PeriodBasics {
public static void main(String[] args) {
Period p = Period.of(1, 2, 3);
System.out.println(p); // P1Y2M3D
System.out.println(p.getYears()); // 1
System.out.println(p.getMonths()); // 2
System.out.println(p.getDays()); // 3
System.out.println(Period.ofWeeks(2)); // P14D
System.out.println(Period.ofMonths(18)); // P18M
System.out.println(Period.ZERO); // P0D
Period parsed = Period.parse("P1Y2M3D");
System.out.println(parsed.equals(p)); // true
}
}Measuring Between Two Dates
Period.between(start, end) tells you how many years, months, and days lie between two LocalDate values. The start date is counted and the end date is not. A range like this, which includes the start and leaves out the end, is called end-exclusive.
import java.time.LocalDate;
import java.time.Period;
public class PeriodBetween {
public static void main(String[] args) {
Period p = Period.between(LocalDate.of(2020, 1, 15), LocalDate.of(2024, 3, 10));
System.out.println(p); // P4Y1M24D
System.out.println(p.getDays()); // 24 (not the total number of days)
LocalDate birthday = LocalDate.of(2000, 6, 15);
LocalDate today = LocalDate.of(2024, 11, 5);
Period age = Period.between(birthday, today);
System.out.println("Age: " + age.getYears() + " years"); // Age: 24 years
System.out.println(age); // P24Y4M21D
}
}Java works this out in steps, the same way a person would count on a calendar.
Zero and Negative Periods
When the end date comes before the start date, the Period is negative. You can check for this with isNegative() and check for an empty Period with isZero().
import java.time.LocalDate;
import java.time.Period;
public class PeriodSigns {
public static void main(String[] args) {
Period back = Period.between(LocalDate.of(2024, 3, 10), LocalDate.of(2024, 3, 1));
System.out.println(back); // P-9D
System.out.println(back.isNegative()); // true
System.out.println(back.negated()); // P9D
Period same = Period.between(LocalDate.of(2024, 1, 1), LocalDate.of(2024, 1, 1));
System.out.println(same.isZero()); // true
}
}Adding a Period to a Date
You add a Period to a date with plus and remove it with minus. Both methods return a new date.
import java.time.LocalDate;
import java.time.Period;
public class PeriodAdd {
public static void main(String[] args) {
LocalDate start = LocalDate.of(2024, 1, 10);
Period trial = Period.ofDays(30);
System.out.println(start.plus(trial)); // 2024-02-09
Period contract = Period.of(1, 6, 0);
System.out.println(start.plus(contract)); // 2025-07-10
System.out.println(start.minus(Period.ofMonths(2))); // 2023-11-10
}
}The Month-End Surprise
Not every month has a 31st day. When adding months would land on a day that does not exist, Java moves back to the last valid day of that month. This is called clamping.
import java.time.LocalDate;
import java.time.Period;
public class MonthEnd {
public static void main(String[] args) {
LocalDate jan31 = LocalDate.of(2024, 1, 31);
Period oneMonth = Period.ofMonths(1);
LocalDate feb = jan31.plus(oneMonth);
System.out.println(feb); // 2024-02-29
System.out.println(feb.plus(oneMonth)); // 2024-03-29
System.out.println(jan31.plus(Period.ofMonths(2))); // 2024-03-31
}
}Adding one month twice gives March 29, but adding two months at once gives March 31. Once the date is clamped to February 29, the original "31st" is lost. If you need a monthly billing date, always add the full number of months to the original start date rather than stepping one month at a time.
Normalizing and Comparing Periods
Since Java does not combine units for you, two Periods that seem equal may not be equal.
import java.time.Period;
public class PeriodNormalize {
public static void main(String[] args) {
Period p = Period.of(1, 14, 40);
System.out.println(p); // P1Y14M40D
System.out.println(p.normalized()); // P2Y2M40D
System.out.println(p.toTotalMonths()); // 26
System.out.println(Period.ofYears(1).equals(Period.ofMonths(12))); // false
System.out.println(Period.ofYears(1).equals(Period.ofMonths(12).normalized())); // true
}
}normalized() turns every 12 months into a year. It leaves the days alone, because a month has no fixed number of days. toTotalMonths() returns years times 12 plus months, and it also ignores days.
Common Mistakes
- Adding a Period to a time-only value.
LocalTime.of(9, 0).plus(Period.ofDays(1))throwsUnsupportedTemporalTypeException, because aLocalTimehas no date. Use Duration for clock times. - Reading
getDays()as a total. It is only the days field. - Throwing away the result.
date.plus(period);on its own does nothing useful. Assign the returned date to a variable. - Expecting one day to always be 24 hours. When you add
Period.ofDays(1)to aZonedDateTime, Java keeps the same local clock time, even if a daylight saving change makes that day 23 or 25 hours long. A later chapter covers this.
Exercise
What does Period.between(LocalDate.of(2023, 5, 20), LocalDate.of(2024, 7, 4)) print, and what does getDays() return?
Show answer
It prints P1Y1M14D. From 2023-05-20, adding 1 year gives 2024-05-20, adding 1 month gives 2024-06-20, and 14 more days reach 2024-07-04. getDays() returns 14.
Exercise
A subscription starts on 2024-03-31. Why does start.plus(Period.ofMonths(1)).plus(Period.ofMonths(1)) give a different date than start.plus(Period.ofMonths(2)), and what are the two results?
Show answer
The first step lands on April 31, which does not exist, so Java clamps it to 2024-04-30. Adding another month then gives 2024-05-30. Adding two months at once goes straight to 2024-05-31. Clamping in the first step lost the original day 31.
Exercise
Does Period.ofMonths(24).equals(Period.ofYears(2)) return true or false? How would you make the comparison return true?
Show answer
It returns false, because Period compares the years, months, and days fields separately. Call normalized() on the months-based Period first: Period.ofMonths(24).normalized() is P2Y, which equals Period.ofYears(2).