计算 Java 8 中两个日期之间的天数 [英] Calculate days between two Dates in Java 8
问题描述
我知道有很多关于如何在 Java 中获取 Date
的问题,但我想要一个使用新 Java 8 Date
API 的示例.我也知道 JodaTime 库,但我想要一种不依赖外部库的方法.
I know there are lots of questions on SO about how to get Date
s 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:
- 防止日期保存时间出错
- 输入是两个
Date
对象(没有时间,我知道LocalDateTime
,但我需要用Date
实例来做到这一点)莉>
- Prevent errors from date savetime
- Inputs are two
Date
objects (without time, I know aboutLocalDateTime
, but I need to do this withDate
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屋!