Java Period Class
The `Period` class is part of the date and time API introduced in Java 8, located in the `java.time` package.
The Period class is mainly used to represent the time interval between two dates, in units of years, months, and days. Unlike the `Duration` class (which represents time-based intervals such as hours, minutes, and seconds), `Period` focuses on date-level differences.
* * *
## Core Features
### 1. Immutability
The `Period` class is immutable, which means that once a `Period` object is created, its value cannot be modified. Any operation on `Period` (such as addition or subtraction) will return a new `Period` instance.
### 2. Date-Based Calculations
`Period` is specifically designed for handling year, month, and day calculations, suitable for scenarios like birthdays, contract periods, etc.
### 3. Collaboration with LocalDate
`Period` is typically used together with the `LocalDate` class to calculate the difference between two dates or add/subtract a period of time to a date.
* * *
## Common Methods
### Creating Period Objects
#### 1. Using the `of()` Method
## Example
Period period = Period.of(1, 2, 3);// 1 year 2 months 3 days
#### 2. Using the `between()` 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. Using the `parse()` Method to Create from a String
## Example
Period period = Period.parse("P1Y2M3D");// ISO-8601 format
### Getting the Parts of a Period
## Example
int years = period.getYears();// Get years
int months = period.getMonths();// Get months
int days = period.getDays();// Get days
### Arithmetic Operations
#### 1. Addition and Subtraction
## Example
Period added = period.plusYears(1).plusMonths(2);
Period subtracted = period.minusDays(5);
#### 2. Checking if Negative
## Example
boolean isNegative = period.isNegative();
#### 3. Normalizing Period
## Example
Period normalized = period.normalized();// Convert months exceeding 12 to 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);
### Checking if a Time Period is Empty
## Example
Period zeroPeriod = Period.of(0, 0, 0);
if(zeroPeriod.isZero()){
System.out.println("This is a zero time 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 of() method
Period period1 = Period.of(1, 2, 15);// 1 year 2 months 15 days
System.out.println("Period 1: "+ period1);
// 2. Using 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 parse() method to create from string
Period period3 = Period.parse("P1Y2M15D");// ISO-8601 format
System.out.println("Parsed Period: "+ period3);
}
}
Output:
Period 1: P1Y2M15D Period between dates: P3Y4M14D Parsed Period: P1Y2M15D
* * *
## Notes
1. **Precision Issue**: `Period` only calculates the differences in years, months, and days, without considering time (hours, minutes, etc.) differences.
2. **Negative Value Handling**: If the end date is earlier than the start date, `Period.between()` will return a negative value.
3. **Month Day Differences**: `Period` calculations consider the day differences between different months (e.g., February has 28 or 29 days).
4. **ISO-8601 Format**: When using the `parse()` method, the string must follow the `PnYnMnD` format (e.g., "P1Y2M3D").
* * *
## Summary
The `Period` class is a powerful tool in the Java date and time API for handling date-based intervals. Through it, developers can easily perform date calculations at the year, month, and day levels, especially suitable for business scenarios requiring precision to the date. Mastering the use of the `Period` class can make your date processing code more concise and readable.
YouTip