Java Tutorials


Java 8 Date Time Class

Period class Usage

   Period Class

Creating a Period Object. Period class factory method

of()

method returns Period object.
Creating a Period object for "10 years 3 months and 33 days"
      		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]

Get years ,months and days from Period Object

    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.
      

plus , minus methods

    

convert string to Period Object using parse method

    

subtract from other termporal object

    

normalize Period Object

    

Difference between two LocalDates using between method

    

      
      Period  p = Period.between(LocalDate.of(1999,1,1),LocalDate.of(2000,2,2))
	System.out.println(p);
	P1Y1M1D

      

ADS