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安全

相關文章
相關標籤/搜索