通过Java日期时间API系列8-----Jdk8中java.time包中的新的日期时间API类的LocalDate源码分析 ,可以看出java8设计非常好,实现接口Temporal, TemporalAdjuster, ChronoLocalDate等,有非常丰富的方法。例如:LocalDateTime:的部分方法:
包含了获取年月日,时分秒纳秒。Date中如果要获取这些信息,必须使用Calendar才可以。现在通过将Date转换为LocalDateTime,就能非常方便,线程安全的获取年月日,时分秒等信息。
public static int getYear(Date date){ return DateTimeConverterUtil.toLocalDateTime(date).getYear(); } public static int getYear(Instant instant){ return DateTimeConverterUtil.toLocalDateTime(instant).getYear(); } public static int getMonth(Date date){ return DateTimeConverterUtil.toLocalDateTime(date).getMonthValue(); } public static int getMonth(Instant instant){ return DateTimeConverterUtil.toLocalDateTime(instant).getMonthValue(); } public static int getDayOfMonth(Date date){ return DateTimeConverterUtil.toLocalDateTime(date).getDayOfMonth(); } public static int getDayOfMonth(Instant instant){ return DateTimeConverterUtil.toLocalDateTime(instant).getDayOfMonth(); } public static int getHour(Date date){ return DateTimeConverterUtil.toLocalDateTime(date).getHour(); } public static int getHour(Instant instant){ return DateTimeConverterUtil.toLocalDateTime(instant).getHour(); } public static int getMinute(Date date){ return DateTimeConverterUtil.toLocalDateTime(date).getMinute(); } public static int getMinute(Instant instant){ return DateTimeConverterUtil.toLocalDateTime(instant).getMinute(); } public static int getSecond(Date date){ return DateTimeConverterUtil.toLocalDateTime(date).getSecond(); } public static int getSecond(Instant instant){ return DateTimeConverterUtil.toLocalDateTime(instant).getSecond(); }
测试类:
@Test public void dateCalculatorGetTest(){ Date date = new Date(); System.out.println(date); System.out.println(DateTimeConverterUtil.toLocalDateTime(date)); System.out.println(DateTimeCalculatorUtil.getYear(date)); System.out.println(DateTimeCalculatorUtil.getMonth(date)); System.out.println(DateTimeCalculatorUtil.getDayOfMonth(date)); System.out.println(DateTimeCalculatorUtil.getHour(date)); System.out.println(DateTimeCalculatorUtil.getMinute(date)); System.out.println(DateTimeCalculatorUtil.getSecond(date)); }
输出:
Sun Jan 12 22:24:07 CST 2020 2020-01-12T22:24:07.681 2020 1 12 22 24 7