Java日期时间API系列14-----Jdk8中java.time包中的新的日期时间API类,java日期计算1,获取年月日时分秒等

  经过Java日期时间API系列8-----Jdk8中java.time包中的新的日期时间API类的LocalDate源码分析 ,能够看出java8设计很是好,实现接口Temporal, TemporalAdjuster, ChronoLocalDate等,有很是丰富的方法。例如:LocalDateTime:的部分方法:html

  

 

包含了获取年月日,时分秒纳秒。Date中若是要获取这些信息,必须使用Calendar才能够。如今经过将Date转换为LocalDateTime,就能很是方便,线程安全的获取年月日,时分秒等信息。java

    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();
    }

 

测试类:git

    @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));
    }

 

输出:github

Sun Jan 12 22:24:07 CST 2020
2020-01-12T22:24:07.681
2020
1
12
22
24
7

 

源代码地址:https://github.com/xkzhangsan/xk-time安全

相关文章
相关标签/搜索