如何检查日期是否超过 30 天?

joh*_*ohn 2 java date jodatime

我有一个java.util.Date我需要检查它是否超过 30 天。检查的最佳方法是什么?

for(Date date: listOfDates) {
  // how to check this date to see whether it is more than 30 days limit
  if(checkDateLimit()) {

  }
}
Run Code Online (Sandbox Code Playgroud)

我在 Java 7 上。

arc*_*rcy 6

这取决于您希望对“30 天”的定义采取何种形式。如果您只想知道给定的日期(在 Java 中,包括精确到毫秒的时间)是否是 30 天(精确到毫秒),那么您可以计算 30 天内有多少毫秒,看看当前日期大于给定日期的毫秒数。

日期通过 getTime() 显示它们的毫秒值。

private boolean olderThan30Days(Date givenDate)
{
  long currentMillis = new Date().getTime();
  long millisIn30Days = 30 * 24 * 60 * 60 * 1000;
  boolean result = givenDate.getTime() < (currentMillis - millisIn30Days);
  return result;
}
Run Code Online (Sandbox Code Playgroud)