java.time.Period is a class that represents a quantity or amount of time in terms of years, months, and days. Here’s a brief guide on how to use it:
1. Creating a Period instance
The Period class provides several static methods named of() and between() to create an instance. To create Period of 1 year, 2 months, and 3 days:
Period period = Period.of(1, 2, 3);
Or you can create a Period using LocalDate:
LocalDate start = LocalDate.of(2020, Month.JANUARY, 1);
LocalDate end = LocalDate.of(2023, Month.MARCH, 31);
Period period = Period.between(start, end);
2. Retrieving Years, Months, and Days
Use the getDays(), getMonths(), and getYears() methods to get the number of days, months, and years in the Period.
int days = period.getDays();
int months = period.getMonths();
int years = period.getYears();
3. Adding/subtracting Period to/from a LocalDate
The LocalDate.plus() or LocalDate.minus() methods can be used to add or subtract a Period from a LocalDate.
LocalDate ld = LocalDate.of(2021, Month.JULY, 1);
Period period = Period.of(1, 2, 3);
LocalDate newDate = ld.plus(period);
In this case, newDate will be 1 year, 2 months, and 3 days after July 1, 2021.
4. Mixing units of time
You can use plusDays(), plusMonths(), or plusYears() to add to a Period.
Period period = Period.of(1, 2, 3);
Period newPeriod = period.plusDays(10);
The newPeriod will then be 1 year, 2 months, and 13 days.
