Java8中计算日期时间差

时间:2022-07-22
本文章向大家介绍Java8中计算日期时间差,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

在 Java中,我们要获取一个时间段的天数,我们可以使用下面几种方式:

  1. Period @since 1.8
  2. Duration @since 1.8
  3. ChronoUnit @since 1.8

一. 参数声明

LocalDate start = LocalDate.of(2020, 1, 1);
LocalDate end = LocalDate.of(2020, 5, 1);

二.Period类

主要通过Period类方法getYears()getMonths()getDays()来计算.

示例:

    /**
     * @Author liuwenxu.com (2020-04-26)
     *
     * @param start
     * @param end
     * @return void
     **/
    private static void testPeriod(LocalDate start, LocalDate end) {

        log.info("startPeriod : {}", start);
        log.info("endPeriod : {}", end);

        Period period = Period.between(start, end);
        log.info("[{}~{})之间共有:{}年,{}月,{}日", start, end, period.getYears(), +period.getMonths(), +period.getDays());
    }

结果:

- startPeriod : 2020-01-01
- endPeriod : 2020-05-01
- [2020-01-01~2020-05-01)之间共有:0年,4月,0日

三.Duration类

提供了使用基于时间的值测量时间量的方法:

天数:toDays(); 小时:toHours(); 分钟:toMinutes(); 秒数:toMillis(); 纳秒:toNanos();

示例: 转换日期时提前一天

    /**
     * @Author liuwenxu.com (2020-04-26)
     *
     * @param start
     * @param end
     * @return void
     **/
    private static void testDuration(LocalDate start, LocalDate end) {

        Instant startInstant = start.atStartOfDay(ZoneId.systemDefault()).toInstant();
        Instant endInstant = end.atStartOfDay(ZoneId.systemDefault()).toInstant();

        log.info("startInstant : {}", startInstant);
        log.info("endInstant : {}", endInstant);

        Duration between = Duration.between(startInstant, endInstant);
        log.info("[{}~{})之间共有:{}天", start, end, between.toDays());

    }

结果:

- startInstant : 2019-12-31T16:00:00Z
- endInstant : 2020-04-30T16:00:00Z
- [2020-01-01~2020-05-01)之间共有:121天

四.ChronoUnit类

ChronoUnit类使用between()方法求在单个时间单位内测量一段时间,例如天数、小时、周或秒等。

示例:

	/**
     * @Author liuwenxu.com (2020-04-26)
     *
     * @param start
     * @param end
     * @return void
     **/
    private static void testChronoUnit(LocalDate start, LocalDate end) {
        log.info("startChronoUnit : {}", start);
        log.info("endChronoUnit : {}", end);

        long daysDiff = ChronoUnit.DAYS.between(start, end);
        log.info("[{}~{})之间共有:{}天", start, end, daysDiff);

    }

结果:

- startInstant : 2020-01-01
- endInstant : 2020-05-01
- [2020-01-01~2020-05-01)之间共有:121天

Q.E.D.