java.time.Period Tutorial with Examples
Period class represents a date-based amount of time in the ISO-8601 calendar system, such as '4 years, 6 months and 15 days'. The ISO-8601 calendar system is the modern civil calendar system used today in most of the world. It is equivalent to the proleptic Gregorian calendar system, in which today's rules for leap years are applied for all time. This class is immutable and thread-safe.
Creating a Period
We can create a Period object by using one of the Period class factory methods:
- static Period of(int years, int months, int days): Obtains a Period representing a number of years, months and days.
- static Period ofDays(int days): Obtains a Period representing a number of days.
- static Period ofMonths(int months): Obtains a Period representing a number of months.
- static Period ofWeeks(int weeks): Obtains a Period representing a number of weeks.
- static Period ofYears(int years): Obtains a Period representing a number of years.
- static Period parse(CharSequence text): Obtains a Period from a text string such as PnYnMnD.
And maybe the most common factory method to create a Period is between() method:
- static Period between(LocalDate startDateInclusive,LocalDate endDateExclusive): Obtains a Period consisting of the number of years, months, and days between two dates.
import java.time.LocalDate;
import java.time.Period;
public class PeriodInitExample {
public static void main(String[] args) {
Period period1 = Period.of(1, 6, 10);
System.out.println("Period1: " + period1);
Period period2 = Period.ofDays(15);
System.out.println("Period2: " + period2);
Period period3 = Period.ofWeeks(15);
System.out.println("Period3: " + period3);
Period period4 = Period.ofMonths(3);
System.out.println("Period4: " + period4);
Period period5 = Period.ofYears(5);
System.out.println("Period5: " + period5);
Period period6 = Period.parse("P5Y3M15D");
System.out.println("Period6: " + period6);
Period period7 = Period.between(LocalDate.of(1979, 12, 9), LocalDate.of(1980, 4, 9));
System.out.println("Period7: " + period7);
}
}
Period1: P1Y6M10D Period2: P15D Period3: P105D Period4: P3M Period5: P5Y Period6: P5Y3M15D Period7: P4M
Accessing Information from a Period
The supported units of a period are YEARS, MONTHS and DAYS. All three fields are always present, but may be set to zero. Those fields can be accessed through these methods:
- int getDays(): Gets the amount of days of this period.
- int getMonths(): Gets the amount of months of this period.
- int getYears(): Gets the amount of years of this period.
Or using get(...) method:
- long get(TemporalUnit unit): Gets the value of the requested unit.
Following function is to get all units supported:
- List<TemporalUnit> getUnits(): Gets the set of units supported by this period.
import java.time.Period;
import java.time.temporal.ChronoUnit;
import java.time.temporal.TemporalUnit;
import java.util.List;
public class PeriodGetExample {
public static void main(String[] args) {
Period period = Period.parse("P3Y6M10D");
System.out.println("Period: " + period);
System.out.println("Years : " + period.getYears());
System.out.println("Months: " + period.getMonths());
System.out.println("Days : " + period.getDays());
System.out.println("YEARS : " + period.get(ChronoUnit.YEARS));
System.out.println("MONTHS: " + period.get(ChronoUnit.MONTHS));
System.out.println("DAYS : " + period.get(ChronoUnit.DAYS));
System.out.println("\n#getUnits():");
List<TemporalUnit> units = period.getUnits();
for (TemporalUnit unit : units) {
System.out.println("- " + unit);
}
}
}
Period: P3Y6M10D Years : 3 Months: 6 Days : 10 YEARS : 3 MONTHS: 6 DAYS : 10 #getUnits(): - Years - Months - Days
Following methods also used to get information about a Period:
- IsoChronology getChronology(): Gets the chronology of this period, which is the ISO calendar system.
- boolean isNegative(): Checks if any of the three units of this period are negative.
- boolean isZero(): Checks if all three units of this period are zero.
- long toTotalMonths(): Gets the total number of months in this period.
import java.time.LocalDate;
import java.time.Period;
public class PeriodInfoExample {
public static void main(String[] args) {
Period period1 = Period.parse("P10Y5M20D");
System.out.println("Period1 : " + period1);
System.out.println("Chronology : " + period1.getChronology());
System.out.println("TotalMonths: " + period1.toTotalMonths());
System.out.println("#isNegative: " + period1.isNegative());
System.out.println("#isZero : " + period1.isZero());
LocalDate localDate1 = LocalDate.of(1980, 4, 9);
Period duration2 = Period.between(localDate1, localDate1);
System.out.println("\nPeriod2 : " + duration2);
System.out.println("#isNegative: " + duration2.isNegative());
System.out.println("#isZero : " + duration2.isZero());
LocalDate localDate2 = LocalDate.of(1979, 12, 9);
Period duration3 = Period.between(localDate1, localDate2);
System.out.println("\nPeriod3 : " + duration3);
System.out.println("#isNegative: " + duration3.isNegative());
System.out.println("#isZero : " + duration3.isZero());
}
}
Period1 : P10Y5M20D Chronology : ISO TotalMonths: 125 #isNegative: false #isZero : false Period2 : P0D #isNegative: false #isZero : true Period3 : P-4M #isNegative: true #isZero : false
Plus/Minus Operations on Period
The Period class also has several methods which can be used to do add/subtract operations:
- Period minus(TemporalAmount amountToSubtract): Returns a copy of this period with the specified period subtracted.
- Period minusDays(long daysToSubtract): Returns a copy of this period with the specified days subtracted.
- Period minusMonths(long monthsToSubtract): Returns a copy of this period with the specified months subtracted.
- Period minusYears(long yearsToSubtract): Returns a copy of this period with the specified years subtracted.
- Period plus(TemporalAmount amountToAdd): Returns a copy of this period with the specified period added.
- Period plusDays(long daysToAdd): Returns a copy of this period with the specified days added.
- Period plusMonths(long monthsToAdd): Returns a copy of this period with the specified months added.
- Period plusYears(long yearsToAdd): Returns a copy of this period with the specified years added.
import java.time.Period;
public class PeriodPlusMinusExample {
public static void main(String[] args) {
Period period = Period.parse("P8Y5M5D");
System.out.println("Period : " + period);
// Adding/subtracting days
System.out.println("10 days before : " + period.minusDays(10));
System.out.println("15 days later : " + period.plusDays(15));
// Adding/subtracting months
System.out.println("12 months before: " + period.minusMonths(12));
System.out.println("6 months later : " + period.plusMonths(6));
// Adding/subtracting years
System.out.println("Minus 10 years : " + period.minusYears(10));
System.out.println("Plus 5 years : " + period.plusYears(5));
// Using Period
System.out.println("5 days before : " + period.minus(Period.ofDays(5)));
System.out.println("10 days later : " + period.plus(Period.ofDays(10)));
}
}
Period : P8Y5M5D 10 days before : P8Y5M-5D 15 days later : P8Y5M20D 12 months before: P8Y-7M5D 6 months later : P8Y11M5D Minus 10 years : P-2Y5M5D Plus 5 years : P13Y5M5D 5 days before : P8Y5M 10 days later : P8Y5M15D
Somehow we cannot using Duration for plus(...) and/or minus(...) methods, the program will throw following error: Exception in thread "main" java.time.DateTimeException: Unit must be Years, Months or Days, but was Seconds
Conclusion
Period normally used for date-based amount between two Dates. If you interested in time-based amount, you need to use Duration instead.