Java8 時間差計算


方式一:

    /**
     * DateTimeFormatter   java 8 線程安全
     * @throws Exception
     */
    @Test
    public void testTimeDiff() throws Exception {
//        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").withZone(ZoneId.of("Asia/Shanghai"));
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
         LocalDateTime startDate = LocalDateTime.parse("2019-07-12 00:00:00", formatter);
         LocalDateTime endDate = LocalDateTime.parse("2019-10-12 02:00:00", formatter);
        // 日期區間
        long days = ChronoUnit.DAYS.between(startDate, endDate);
        //
        long month = ChronoUnit.MONTHS.between(startDate, endDate);
        //
        long year = ChronoUnit.YEARS.between(startDate, endDate);
        long hour = ChronoUnit.HOURS.between(startDate, endDate);
        long min = ChronoUnit.MINUTES.between(startDate, endDate);
        System.err.println( "相差MIN:"+min);
        System.err.println( "相差hour:"+hour);
        System.err.println( "相差days :"+days);
        System.err.println( "相差month :"+month);
        System.err.println( "相差year:"+year);
        
    }

 

 

 

public void test() {
        try {
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date now = df.parse("2019-03-26 13:31:40");//當前時間
            Date date = df.parse("2004-01-02 11:30:24");//過去
            long l = now.getTime() - date.getTime();
            long day = l / (24 * 60 * 60 * 1000);
            long hour = (l / (60 * 60 * 1000) - day * 24);
            long min = ((l / (60 * 1000)) - day * 24 * 60 - hour * 60);
            long s = (l / 1000 - day * 24 * 60 * 60 - hour * 60 * 60 - min * 60);
            System.out.println("" + day + "" + hour + "小時" + min + "" + s + "");
        } catch (Exception e) {

        }

    }

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM