检查 java.util.Date 与当前时间相比是否早于 30 天的最佳方法?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29252949/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Best Way to check if a java.util.Date is older than 30 days compared to current moment in time?
提问by Steve Waters
Here's what I want to do:
这是我想要做的:
Date currentDate = new Date();
Date eventStartDate = event.getStartDate();
How to check if eventStartDate is more than 30 days older than currentDate?
如何检查 eventStartDate 是否比 currentDate 早 30 天?
I'm using Java 8, Calendar isn't preferred.
我使用的是 Java 8,日历不是首选。
Time zone is ZoneId.systemDefault().
时区是 ZoneId.systemDefault()。
回答by Jon Skeet
Okay, assuming you really want it to be "30 days" in the default time zone, I would use something like:
好的,假设您真的希望它在默认时区为“30 天”,我会使用以下内容:
// Implicitly uses system time zone and system clock
ZonedDateTime now = ZonedDateTime.now();
ZonedDateTime thirtyDaysAgo = now.plusDays(-30);
if (eventStartDate.toInstant().isBefore(thirtyDaysAgo.toInstant())) {
...
}
If "thirty days ago" was around a DST change, you need to check that the documentation for plusDays
gives you the behaviour you want:
如果“三十天前”是围绕 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.
转换回 ZonedDateTime 时,如果本地日期时间重叠,则尽可能保留偏移量,否则将使用较早的偏移量。如果在间隙中,本地日期时间将根据间隙的长度向前调整。
Alternatively you couldsubtract 30 "24 hour" days, which would certainly be simpler, but may give unexpected results in terms of DST changes.
或者,您可以减去 30 个“24 小时”天,这当然会更简单,但可能会在 DST 更改方面产生意想不到的结果。
回答by gaRos
You could try this:
你可以试试这个:
Date currentDate = new Date();
Date eventStartDate = event.getStartDate();
long day30 = 30l * 24 * 60 * 60 * 1000;
boolean olderThan30 = currentDate.before(new Date((eventStartDate .getTime() + day30)));
It's disguisting, but it should do the job!
它很伪装,但它应该可以完成工作!