gpt4 book ai didi

java - 与当前时刻相比,检查 java.util.Date 是否早于 30 天的最佳方法?

转载 作者:搜寻专家 更新时间:2023-11-01 01:12:32 24 4
gpt4 key购买 nike

这是我想做的:

Date currentDate = new Date();
Date eventStartDate = event.getStartDate();

如何检查 eventStartDate 是否比 currentDate 早 30 天以上?

我使用的是 Java 8,日历不是首选。

时区是 ZoneId.systemDefault()。

最佳答案

好吧,假设您真的希望默认时区为“30 天”,我会使用如下内容:

// Implicitly uses system time zone and system clock
ZonedDateTime now = ZonedDateTime.now();
ZonedDateTime thirtyDaysAgo = now.plusDays(-30);

if (eventStartDate.toInstant().isBefore(thirtyDaysAgo.toInstant())) {
...
}

如果“三十天前”是在 DST 更改前后,您需要检查 plusDays 的文档是否提供了您想要的行为:

When converting back to ZonedDateTime, if the local date-time is in an overlap, then the offset will be retained if possible, otherwise the earlier offset will be used. If in a gap, the local date-time will be adjusted forward by the length of the gap.

或者,您可以减去 30 个“24 小时”天,这肯定会更简单,但可能会在 DST 更改方面产生意想不到的结果。

关于java - 与当前时刻相比,检查 java.util.Date 是否早于 30 天的最佳方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29252949/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com