OCA Java SE 8 Core Java APIs - Java Period








There are five ways to create a Period class:

Period annually = Period.ofYears(1);               // every 1 year 
Period quarterly = Period.ofMonths(3);               // every 3 months 
Period everyThreeWeeks = Period.ofWeeks(3);          // every 3 weeks 
Period everyOtherDay = Period.ofDays(2);          // every 2 days 
Period everyYearAndAWeek = Period.of(1, 0, 7);          // every year and 7 days 

There's one catch. You cannot chain methods when creating a Period.

The following code looks like it is equivalent to the everyYearAndAWeek example, but it's not. Only the last method is used because the Period.ofXXX methods are static methods.

Period wrong = Period.ofYears(1).ofWeeks(1);          // every week 

of() method allows us to pass in the number of years, months, and days.

They are all included in the same period.

Period is a day or more of time while Duration is for smaller units of time.

For Duration, you can specify the number of days, hours, minutes, seconds, or nanoseconds.

Let's look at some code:

3: LocalDate date = LocalDate.of(2015, 1, 20); 
4: LocalTime time = LocalTime.of(6, 15); 
5: LocalDateTime dateTime = LocalDateTime.of(date, time); 
6: Period period = Period.ofMonths(1); 
7: System.out.println(date.plus(period));          // 2015-02-20 
8: System.out.println(dateTime.plus(period));          // 2015-02-20T06:15 
9: System.out.println(time.plus(period));   // UnsupportedTemporalTypeException 

Last time tries to add a month to an object that only has a time. This won't work. Java throws an exception and complains the Unsupported unit: Months.