计算 Java 8 中两个日期之间的天数 [英] Calculate days between two Dates in Java 8

查看:51
本文介绍了计算 Java 8 中两个日期之间的天数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道有很多关于如何在 Java 中获取 Date 的问题,但我想要一个使用新 Java 8 Date API 的示例.我也知道 JodaTime 库,但我想要一种不依赖外部库的方法.

I know there are lots of questions on SO about how to get Dates in Java, but I want an example using new Java 8 Date API. I also know about the JodaTime library, but I want a method without relying on external libraries.

该功能需要符合这些限制:

The function needs to be compliant with these restrictions:

  1. 防止日期保存时间出错
  2. 输入是两个 Date 对象(没有时间,我知道 LocalDateTime,但我需要用 Date 实例来做到这一点)
  1. Prevent errors from date savetime
  2. Inputs are two Date objects (without time, I know about LocalDateTime, but I need to do this with Date instances)

推荐答案

如果您想要逻辑日历天,请使用 DAYS.between() 方法来自 java.time.temporal.ChronoUnit:

If you want logical calendar days, use DAYS.between() method from java.time.temporal.ChronoUnit:

LocalDate dateBefore;
LocalDate dateAfter;
long daysBetween = DAYS.between(dateBefore, dateAfter);

如果您想要字面的 24 小时天,(持续时间),您可以使用 Duration 类:

If you want literal 24 hour days, (a duration), you can use the Duration class instead:

LocalDate today = LocalDate.now()
LocalDate yesterday = today.minusDays(1);
// Duration oneDay = Duration.between(today, yesterday); // throws an exception
Duration.between(today.atStartOfDay(), yesterday.atStartOfDay()).toDays() // another option

有关详细信息,请参阅本文档.

For more information, refer to this document.

这篇关于计算 Java 8 中两个日期之间的天数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆