Java Period Class

PeriodThe class is part of the date-time API introduced in Java 8, located injava.timethe package.

The Period class is mainly used to represent the time interval between two dates, in units of years, months, and days. UnlikeDurationclass (which represents time-based intervals such as hours, minutes, and seconds),Periodit focuses on differences at the date level.


Core Features

1. Immutability

PeriodThe class is immutable, meaning that once anPeriodobject is created, its value cannot be changed. AnyPeriodoperation (such as addition or subtraction) will return a newPeriodinstance.

2. Date-based calculations

PeriodIt is specifically used for calculations involving years, months, and days, making it suitable for scenarios such as birthdays and contract durations.

3. Integration with LocalDate

PeriodIt is usually used with theLocalDateclass to calculate the difference between two dates or to add/subtract a period of time to/from a date.


Common Methods

Creating Period Objects

1. Usingof()method

Example

Period period = Period.of(1, 2, 3); // 1 year 2 months 3 days

2. Usingbetween()method to calculate the interval between two dates

Example

LocalDate startDate = LocalDate.of(2020, 1, 1);
LocalDate endDate = LocalDate.of(2021, 3, 4);
Period period = Period.between(startDate, endDate);

3. Usingparse()method to create from a string

Example

Period period = Period.parse("P1Y2M3D"); // ISO-8601 format

Getting the components of a Period

Example

int years = period.getYears();  // Get the number of years
int months = period.getMonths(); // Get the number of months
int days = period.getDays();    // Get the number of days

Operations

1. Addition and subtraction operations

Example

Period added = period.plusYears(1).plusMonths(2);
Period subtracted = period.minusDays(5);

2. Determine whether it is negative

Example

boolean isNegative = period.isNegative();

3. Normalize the Period

Example

Period normalized = period.normalized(); // Convert months exceeding 12 into years

Practical Application Examples

Calculating the interval between two dates

Example

LocalDate birthDate = LocalDate.of(1990, 5, 15);
LocalDate currentDate = LocalDate.now();
Period age = Period.between(birthDate, currentDate);
System.out.printf("Age: %d years %d months %d days",
    age.getYears(), age.getMonths(), age.getDays());

Adding a Period to a date

Example

LocalDate today = LocalDate.now();
Period twoMonths = Period.ofMonths(2);
LocalDate futureDate = today.plus(twoMonths);

Check whether the period is zero

Example

Period zeroPeriod = Period.of(0, 0, 0);
if (zeroPeriod.isZero()) {
    System.out.println("This is a zero period");
}

Comprehensive Example

Example

import java.time.Period;
import java.time.LocalDate;

public class PeriodDemo {
    public static void main(String[] args) {
        // Several ways to create Period objects
       
        // 1. Using the of() method
        Period period1 = Period.of(1, 2, 15); // 1 year 2 months 15 days
        System.out.println("Period 1: " + period1);
       
        // 2. Using the between() method to calculate the period between two dates
        LocalDate startDate = LocalDate.of(2020, 1, 1);
        LocalDate endDate = LocalDate.of(2023, 5, 15);
        Period period2 = Period.between(startDate, endDate);
        System.out.println("Period between dates: " + period2);
       
        // 3. Using the parse() method to create from a string
        Period period3 = Period.parse("P1Y2M15D"); // ISO-8601 format
        System.out.println("Parsed Period: " + period3);
    }
}

The output is:

Period 1: P1Y2M15D
Period between dates: P3Y4M14D
Parsed Period: P1Y2M15D

Notes

  1. Precision issues:PeriodIt only calculates differences in years, months, and days, ignoring differences in time (hours, minutes, etc.).
  2. Negative value handling: If the end date is earlier than the start date,Period.between()a negative value will be returned.
  3. Differences in days per month:PeriodThe calculation accounts for the varying number of days in different months (e.g., February has 28 or 29 days).
  4. ISO-8601 format: When using theparse()method, the string must follow thePnYnMnDformat (e.g., "P1Y2M3D").

Summary

PeriodThe class is a powerful tool for handling date-based intervals in the Java date-time API. Through it, developers can conveniently perform date calculations at the year, month, and day level, making it especially suitable for business scenarios that require date-level precision. MasteringPeriodthe use of this class can make your date-handling code more concise and readable.

Other Extensions