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) {

        }

    }

 

原文地址:https://www.cnblogs.com/lshan/p/12493313.html