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
    
    一颗安安静静的小韭菜。文中如果有什么错误,欢迎指出。
  • 相关阅读:
    在腾讯云上使用URLOS一键安装Discuz! Q
    共享容器——URLOS最新发布的一项超强功能
    在群晖NAS上运行URLOS之后竟然能安装Discuz! Q!!
    Discuz!Q回归,如何一键安装Discuz!Q
    Docker管理面板-URLOS(易用、高效、强大)
    CentOS下Subversion(SVN)的快速安装与配置
    通过URLOS安装Redis缓存为wordpress网站提速
    5分钟快速安装Redmine项目管理软件
    Python3+HTMLTestRunner+SMTP生成测试报告后发送邮件
    Python3+HTMLTestRunner生成html测试报告时报错HTMLTestRunner.py line 687, in generateReport  self.stream.write(output.encode('utf8'))
  • 原文地址:https://www.cnblogs.com/c-Ajing/p/13448336.html
Copyright © 2011-2022 走看看