• 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
    
    一颗安安静静的小韭菜。文中如果有什么错误,欢迎指出。
  • 相关阅读:
    Android 基于人脸识别 SDK使用总结
    基于虹软人脸识别Demo android人脸识别
    Android Arcface 2.0人脸识别注册失败问题
    C#人脸识别之人脸特征值的提取及识别
    Arcface demo
    人脸识别基于Android
    基于Android 虹软人脸、人证对比,活体检测
    虹软AI 人脸识别SDK接入 — 性能优化篇(多线程)
    Android 安卓人脸识别(百度人脸识别)快速集成采坑
    [mysql 存储过程]MySQL存储过程详解 mysql 存储过程
  • 原文地址:https://www.cnblogs.com/c-Ajing/p/13448336.html
Copyright © 2020-2023  润新知