码迷,mamicode.com
首页 > 编程语言 > 详细

Java8 时间差计算

时间:2020-03-14 18:14:00      阅读:377      评论:0      收藏:0      [点我收藏+]

标签:pattern   get   print   Matter   lda   安全   int   parse   throw   

方式一:

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

        }

    }

 

 

 

Java8 时间差计算

标签:pattern   get   print   Matter   lda   安全   int   parse   throw   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!