Java 8 Time API 示例: MonthDay、Month、OffsetDateTime和OffsetTime
jopen
10年前
MonthDay, Month, OffsetDateTime 和 OffsetTime 已经引入 Java 8 在 time API 中。MONTHDAY代表了月份和日期的组合。Month 是存储月份的所有字段的枚举。 OffsetDateTime表示带偏移的日期和时间,OffsetTime表示时间偏置。
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)); } }Find the output.Output
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")); } }Find the output.Output
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()); } }Find the output.Output
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"); } }Find the outputOutput
16 hour 39 minute 24 second