Java 8 Time API : Period, Year, YearMonth and ZonedDateTime
October 31, 2014
This page provides example of Java 8 API like Period, Year, YearMonth and ZonedDateTime. These are new classes introduced in java 8. Period represents a time period. Year class represents an year and in the same way YearMonth represents year and month. ZonedDateTime represents date and time with zone. Find the example for these classes.
java.time.Period
Period is the amount of time in different unit like year, month or days. An example of period can be like 1 year 5 month 10 days.PeriodDemo.java
package com.cp.time; import java.time.LocalDate; import java.time.Period; public class PeriodDemo { public static void main(String[] args) { LocalDate start = LocalDate.now(); System.out.println("Period.between:"+Period.between(start, LocalDate.MAX).getDays()); System.out.println("Period.ofDays:"+Period.ofDays(5).getDays()); } }
Period.between:19 Period.ofDays:5
java.time.Year
Year class represents year like 2014. This class plays only with year. We can use it to know leap year or can fetch the current year.YearDemo.java
package com.cp.time; import java.time.Year; public class YearDemo { public static void main(String[] args) { System.out.println("Year.now():"+Year.now()); System.out.println("Year.MAX_VALUE:"+Year.MAX_VALUE); System.out.println("Year.isLeap(2014):"+Year.isLeap(2014)); System.out.println("Year.isLeap(2016):"+Year.isLeap(2016)); } }
Year.now():2014 Year.MAX_VALUE:999999999 Year.isLeap(2014):false Year.isLeap(2016):true
java.time.YearMonth
YearMonth is the class that represents the combination of year and month like 2014-09. This class provides methods to get year and month for a given date string.YearMonthDemo.java
package com.cp.time; import java.time.YearMonth; public class YearMonthDemo { public static void main(String[] args) { System.out.println("YearMonth.now():"+YearMonth.now()); System.out.println("getMonthValue():"+YearMonth.parse("2014-09").getMonthValue()); System.out.println("getYear():"+YearMonth.parse("2014-09").getYear()); System.out.println("isLeapYear():"+YearMonth.parse("2014-09").isLeapYear()); } }
YearMonth.now():2014-09 getMonthValue():9 getYear():2014 isLeapYear():false
java.time.ZonedDateTime
ZonedDateTime class represents date and time with zone. The example can be 2014-09-12T18:32:29.636+05:30[Asia/Calcutta]. This class provides the methods to get year, month, day, hour, minute, seconds and zone offset.ZonedDateTimeDemo.java
package com.cp.time; import java.time.ZonedDateTime; public class ZonedDateTimeDemo { public static void main(String[] args) { System.out.println(ZonedDateTime.now()); ZonedDateTime zdt = ZonedDateTime.parse("2014-09-12T10:15:30+01:00[Europe/Paris]"); System.out.println("getDayOfYear:"+zdt.getDayOfYear()); System.out.println("zdt.getYear():"+zdt.getYear()); } }
2014-09-12T18:32:29.636+05:30[Asia/Calcutta] getDayOfYear:255 zdt.getYear():2014