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

Best Way to check if a java.util.Date is older than 30 days compared to current moment in time?

这是我想要做的:

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

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

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

时区是 ZoneId.systemDefault()。

你可以试试这个:

Date currentDate = new Date();
Date eventStartDate = event.getStartDate();
long day30 = 30l * 24 * 60 * 60 * 1000;
boolean olderThan30 = currentDate.before(new Date((eventStartDate .getTime() + day30)));

这很丑陋,但它应该可以完成工作!

好吧,假设你真的希望它在默认时区是“30 天”,我会使用类似的东西:

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

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

如果 "thirty days ago" 是夏令时更改,您需要检查 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 更改方面产生意想不到的结果。

fun isOlderThan(interval: Int,previousTime : Long, currentTime: Long): Boolean {
    val currentDate = Date(currentTime)
    val previousDate = Date(previousTime)

    val diffCalculate = abs(currentDate.time - previousDate.time)
    val diffDays = diffCalculate / (24 * 60 * 60 * 1000)

    return diffDays > interval
}

使用

val dateFormat = SimpleDateFormat("yyy-MM-dd")
val oldDate = dateFormat.parse("2022-02-01")

if(isOlderThan(7,oldDate.time,System.currentTimeMillis()){
  Log.d("OLD CHECK","Old date is 7 days old")
}else{
  Log.d("OLD CHECK","Old day is not 7 days old")
}