我在一个变量中有一个日期时间。现在我想检查上一个日期时间是否在当前时间的二十分钟之前。我该怎么办?
Date previous = myobj.getPreviousDate();
Date now = new Date();
//check if previous was before 20 minutes from now ie now-previous >=20
我们怎么做?
答案 0 :(得分:59)
使用
if (now.getTime() - previous.getTime() >= 20*60*1000) {
...
}
或者,更详细,但也许更容易阅读:
import static java.util.concurrent.TimeUnit.*;
...
long MAX_DURATION = MILLISECONDS.convert(20, MINUTES);
long duration = now.getTime() - previous.getTime();
if (duration >= MAX_DURATION) {
...
}
答案 1 :(得分:19)
使用Joda Time:
boolean result = Minutes.minutesBetween(new DateTime(previous), new DateTime())
.isGreaterThan(Minutes.minutes(20));
答案 2 :(得分:6)
您应该使用Calendar对象而不是Date:
Calendar previous = Calendar.getInstance();
previous.setTime(myobj.getPreviousDate());
Calendar now = Calendar.getInstance();
long diff = now.getTimeInMillis() - previous.getTimeInMillis();
if(diff >= 20 * 60 * 1000)
{
//at least 20 minutes difference
}
答案 3 :(得分:5)
Java 8解决方案:
private static boolean isAtleastTwentyMinutesAgo(Date date) {
Instant instant = Instant.ofEpochMilli(date.getTime());
Instant twentyMinutesAgo = Instant.now().minus(Duration.ofMinutes(20));
try {
return instant.isBefore(twentyMinutesAgo);
} catch (IOException e) {
throw new IllegalStateException(e);
}
}
答案 4 :(得分:1)
以毫秒为单位获取时间,并检查差异:
long diff = now.getTime() - previous.getTime();
if (diff > 20L * 60 * 1000) {
// ...
}
另一种解决方案可能是使用Joda时间。