java8中计算时间日期间隔几种常见方法介绍

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

1.ChronoUnit类

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

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

运行结果:

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

2.Period类

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

	@Test
    public void testPeriod) {
        LocalDate startDate = LocalDate.of2020, Month.APRIL, 6);
        System.out.println"开始时间:" + startDate);
        LocalDate endDate = LocalDate.now);
        Period period = Period.betweenstartDate, 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.plusDuration.ofSeconds30)); // 在当前时间上加上30s
        System.out.println"endtInstant : " + endtInstant);
        Duration duration = Duration.betweenstartInstant, 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

一颗安安静静的小韭菜。文中如果有什么错误,欢迎指出。

Published by

风君子

独自遨游何稽首 揭天掀地慰生平