In this blog post, We will cover the Java.time.Period Class with examples
When working with Date and Time API in java8, There is a requirement to find out the amount of time between two dates is a common requirement
The period is measured in years, months, days and time duration is measured in. It is value based class. So two objects of Period equality check might produce unpredictable results.
public final class Period extends Object implements ChronoPeriod,
The period is Date based measurement of time and it measures in Years, Months and Days Duration is Time based measurement of time and measured in hours, minutes, seconds and nanoseconds Period is used for humanly readable date measurement like years/months Duration is more suitable for machine-based timing measurement for nanoseconds calculations. Finding the age of a person is an example for Period.
There are various examples of the usage of Period.
The period object can be created using creation methods.
of(), ofMonths(), ofDays(),ofYears() methods are used to create a instance of period.
Period ofYears = Period.ofYears(5);
Period ofMonths = Period.ofMonths(11);
Period ofDays = Period.ofDays(20);
Period ofWeeks = Period.ofWeeks(6);
Period periodInYearMonthsTDays = Period.of(5, 11, 25);
System.out.println("Total Period: " + periodInYearMonthsTDays);
Total Period: P5Y11M25D
minus() minusDays() minusMonths() minusYears() are substracting specific units to current date. plus() plusDays() plusMonths() plusYears() are adding specific units to current date.
LocalDate localDate = LocalDate.now();
LocalDate add5Days = localDate.plus(Period.ofDays(5));
System.out.println("Add 5 days"+add5Days);
// date before one week
LocalDate oneweekbefore = localDate.minus(Period.ofWeeks(1));
System.out.println("substract one week "+oneweekbefore);
// Number of dates between two dates
Period period = Period.between(oneweekbefore, add5Days);
System.out.println("difference in days"+period.getDays());
System.out.println("difference in months "+period.getMonths());
Add 5 days2018-09-02
substract one week 2018-08-21
difference in days12
difference in months 0
The period class provides various methods getYears() - return the number of years of this period getMonths() - return number of months of this period getDays() - return number of days of this period
LocalDate currentDate = LocalDate.now();
LocalDate birthday = LocalDate.of(1995, Month.JANUARY, 1);
Period period = Period.between(birthday, currentDate);
System.out.println("Age is " + period.getYears() + " years, " + period.getMonths() +
" months, and " +period.getDays() +
" days old");
Age is 23 years, 7 months, and 27 days old