zoukankan      html  css  js  c++  java
  • java8中计算时间日期间隔几种常见方法介绍

    在平时的开发工作中免不了会进行时间日期间隔计算,下面简单介绍几个在java8中用于计算时间日期间隔的类和方法:

    1.ChronoUnit类

    使用ChronoUnit类可以快速方便的计算出两个时间日期之间的间隔天数,示例代码:

    	@Test
        public void testChronoUnit() {
            LocalDate startDate = LocalDate.of(2020, Month.APRIL, 6);
            System.out.println("开始时间:" + startDate);
            LocalDate endDate = LocalDate.now();
            System.out.println("结束时间:" + endDate);
            long days = ChronoUnit.DAYS.between(startDate, endDate); // 获取间隔天数
            System.out.println("间隔天数:" + days);
        }
    

    运行结果:

    开始时间:2020-04-06
    结束时间:2020-06-10
    间隔天数:65
    

    2.Period类

    使用Period类可以很方便的计算两个时间日期之间间隔的年月日,可以用作快速计算年龄,示例代码:

    	@Test
        public void testPeriod() {
            LocalDate startDate = LocalDate.of(2020, Month.APRIL, 6);
            System.out.println("开始时间:" + startDate);
            LocalDate endDate = LocalDate.now();
            Period period = Period.between(startDate, endDate);
            System.out.println("结束时间:" + endDate);
            int years = period.getYears();// 获取间隔年数
            int months = period.getMonths();// 获取间隔的月数
            int days = period.getDays(); // 获取间隔的天数
            System.out.println("间隔时间--> " + years + "年" + months + "月" + days + "天");
        }
    

    运行结果:

    开始时间:2020-04-06
    结束时间:2020-06-10
    间隔时间--> 0年2月4天
    

    3.Duration类

    Duration类计算两个时间日期间隔的数据更为精准,可以计算到秒,甚至是纳秒,示例代码:

    	@Test
        public void testDuration() {
            Instant startInstant = Instant.now();
            System.out.println("startInstant : " + startInstant);
            Instant endtInstant = startInstant.plus(Duration.ofSeconds(30)); // 在当前时间上加上30s
            System.out.println("endtInstant : " + endtInstant);
            Duration duration = Duration.between(startInstant, endtInstant);
            long days = duration.toDays();
            System.out.println("间隔天数:" + days);
            long seconds = duration.getSeconds();
            System.out.println("间隔秒数:" + seconds);
            long millis = duration.toMillis();
            System.out.println("间隔毫秒数:" + millis);
            long nanos = duration.toNanos();
            System.out.println("间隔纳秒数:" + nanos);
        }
    

    运行结果:

    startInstant : 2020-06-10T06:51:00.389Z
    endtInstant : 2020-06-10T06:51:30.389Z
    间隔天数:0
    间隔秒数:30
    间隔毫秒数:30000
    间隔纳秒数:30000000000
    
    一颗安安静静的小韭菜。文中如果有什么错误,欢迎指出。
  • 相关阅读:
    winform 通过左右键,或enter键做类似Tab键的功能
    向表中插入查询结果
    创建Oracle job的一些注意事项
    多数据库独立主机的配置
    图形码验证
    JavaScript中的trycatchfinally
    ASP.Net生成后台脚本的问题的解决办法
    10个你未必知道的CSS技巧
    学习JQuery的$.Ready()与OnLoad事件比较[转]
    风雨20年:我所积累的20条编程经验[csdn]
  • 原文地址:https://www.cnblogs.com/c-Ajing/p/13448336.html
Copyright © 2011-2022 走看看