The java.time.Period class is used to measures time in years, months and days.
Java Period class methods
| Method |
Description |
| Temporal addTo(Temporal temporal) |
It is used to add this period to the specified temporal object. |
| long get(TemporalUnit unit) |
It is used to get the value of the requested unit. |
| int getYears() |
It is used to get the amount of years of this period. |
| boolean isZero() |
It is used to check if all three units of this period are zero. |
| Period minus(TemporalAmount amountToSubtract) |
It is used to return a copy of this period with the specified period subtracted. |
| static Period of(int years, int months, int days) |
It is used to obtain a Period representing a number of years, months and days. |
| Period plus(TemporalAmount amountToAdd) |
It is used to return a copy of this period with the specified period added. |
Example
package com.w3schools;
import java.time.LocalDate;
import java.time.Period;
import java.time.temporal.Temporal;
public class TestExample {
public static void main(String args[]){
Period period = Period.ofDays(24);
Temporal temporal = period.addTo(LocalDate.now());
System.out.println(temporal);
//plus() method
System.out.println(period.plus(Period.ofDays(10)));
//minus() method
System.out.println(period.minus(Period.ofDays(5)));
}
} |
package com.w3schools;
import java.time.LocalDate;
import java.time.Period;
import java.time.temporal.Temporal;
public class TestExample {
public static void main(String args[]){
Period period = Period.ofDays(24);
Temporal temporal = period.addTo(LocalDate.now());
System.out.println(temporal);
//plus() method
System.out.println(period.plus(Period.ofDays(10)));
//minus() method
System.out.println(period.minus(Period.ofDays(5)));
}
}
Output