Java 8 Time API : MonthDay, Month, OffsetDateTime and OffsetTime
October 18, 2014
MonthDay, Month, OffsetDateTime and OffsetTime has been introduced in Java 8 in time API. MonthDay represents the combination of month and day. Month is an enum that stores all the fields of month. OffsetDateTime represents date and time with offset and OffsetTime represents time with offset
java.time.MonthDay
MonthDay represents the combination of the month and day. This class does not provide year. In the example I am showing some uses and working of MonthDay.MonthDayDemo.java
package com.cp.time; import java.time.MonthDay; public class MonthDayDemo { public static void main(String[] args) { MonthDay mday = MonthDay.now(); System.out.println(mday.getDayOfMonth()); System.out.println(mday.getMonth()); System.out.println(mday.atYear(2014)); } }
11 SEPTEMBER 2014-09-11
java.time.Month
Month is an enum and represents the complete months of the year. Find the uses of Month enum.MonthDemo.java
package com.cp.time; import java.time.Month; public class MonthDemo { public static void main(String[] args) { System.out.println(Month.MARCH); System.out.println(Month.MARCH.getValue()); System.out.println(Month.of(3)); System.out.println(Month.valueOf("MARCH")); } }
MARCH 3 MARCH MARCH
java.time.OffsetDateTime
OffsetDateTime represents all date and time fields. This class represents date and time with an offset. Find the uses of the OffsetDateTime.OffsetDateTimeDemo.java
package com.cp.time; import java.time.OffsetDateTime; public class OffsetDateTimeDemo { public static void main(String[] args) { OffsetDateTime offsetDT = OffsetDateTime.now(); System.out.println(offsetDT.getDayOfMonth()); System.out.println(offsetDT.getDayOfYear()); System.out.println(offsetDT.getDayOfWeek()); System.out.println(offsetDT.toLocalDate()); } }
11 254 THURSDAY 2014-09-11
java.time.OffsetTime
OffsetTime represents time with an offset that can be viewed as hour-minute-second-offset. Find the use of OffsetTime.OffsetTimeDemo.java
package com.cp.time; import java.time.OffsetTime; public class OffsetTimeDemo { public static void main(String[] args) { OffsetTime offTime = OffsetTime.now(); System.out.println(offTime.getHour() +" hour"); System.out.println(offTime.getMinute() +" minute"); System.out.println(offTime.getSecond() +" second"); } }
16 hour 39 minute 24 second