Java Tutorials
Period Class
of()
method returns Period object.Period p = Period.of(10,3,33); System.out.println(p); P10Y3M33D
P stands for Period
Y stands for Years
M stands for Months
D stands for Days
p.getUnits() method returns units supported by Period object,
i.e [Years, Months, Days]
Period object provides getYears(),getMonths(),getDays() methods to extract individual fields or units.
System.out.println(p.getYears()); 10 Yrs System.out.println(p.getMonths()); 3 Months System.out.println(p.getDays()); 33 Days
Period object supports another method called toTotalMonths() method, Which returns total Number of Months, i.e Years * 12 + Months
long months = p.toTotalMonths(); // i.e 10 Yrs and 3 months as 10*12+3 = 123 System.out.println("Total Months="+months); Total Months=123 Note: toTotalMonths() method ignoring Number of Days in this case 33 days are being ignored.
Period p = Period.between(LocalDate.of(1999,1,1),LocalDate.of(2000,2,2)) System.out.println(p); P1Y1M1D
ADS