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

Creating Period Objects: ofYears, ofMonths, ofWeeks, ofDays

Use factory methods to create Period instances representing date-based amounts like years, months, and days.

Creating Period Objects: ofYears, ofMonths, ofWeeks, ofDays

You'll learn how to create Period instances using factory methods to represent date-based amounts like years, months, weeks, and days.

Understanding Period Creation

While Duration measures time-based amounts (hours, minutes, seconds), Period represents date-based amounts. Java provides convenient factory methods to create Period objects for common calendar units without needing to specify all three components (years, months, days) at once.

The Four Factory Methods

Each factory method creates a Period with a specific unit set, leaving other units at zero:

  • Period.ofYears(int years) – Creates a period of N years
  • Period.ofMonths(int months) – Creates a period of N months
  • Period.ofWeeks(int weeks) – Creates a period of N weeks (converted to days: weeks × 7)
  • Period.ofDays(int days) – Creates a period of N days
Period threeYears = Period.ofYears(3);      // P3Y
Period sixMonths = Period.ofMonths(6);      // P6M
Period twoWeeks = Period.ofWeeks(2);        // P14D (weeks converted to days)
Period tenDays = Period.ofDays(10);         // P10D

// Add them to dates
LocalDate start = LocalDate.of(2024, 1, 15);
LocalDate plusYears = start.plus(threeYears);    // 2027-01-15
LocalDate plusMonths = start.plus(sixMonths);    // 2024-07-15
LocalDate plusWeeks = start.plus(twoWeeks);      // 2024-01-29

Weeks Are Special

Notice that ofWeeks() internally converts to days (2 weeks = 14 days). Period stores only years, months, and days—there's no separate "weeks" field.

Period weeks = Period.ofWeeks(3);
System.out.println(weeks.getDays());  // 21 (not stored as weeks)

Key Takeaway: Use Period.ofYears(), ofMonths(), ofWeeks(), and ofDays() factory methods to create date-based periods for single units; these provide clear, readable code for common calendar calculations.