我在一个变量之前有一个日期时间.现在我想检查之前的日期时间是否在当前时间的二十分钟之前.我该怎么做?
Date previous = myobj.getPreviousDate();
Date now = new Date();
//check if previous was before 20 minutes from now ie now-previous >=20
Run Code Online (Sandbox Code Playgroud)
我们怎么做?
aio*_*obe 65
使用
if (now.getTime() - previous.getTime() >= 20*60*1000) {
...
}
Run Code Online (Sandbox Code Playgroud)
或者,更详细,但也许更容易阅读:
import static java.util.concurrent.TimeUnit.*;
...
long MAX_DURATION = MILLISECONDS.convert(20, MINUTES);
long duration = now.getTime() - previous.getTime();
if (duration >= MAX_DURATION) {
...
}
Run Code Online (Sandbox Code Playgroud)
dog*_*ane 20
使用Joda时间:
boolean result = Minutes.minutesBetween(new DateTime(previous), new DateTime())
.isGreaterThan(Minutes.minutes(20));
Run Code Online (Sandbox Code Playgroud)
您应该使用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
}
Run Code Online (Sandbox Code Playgroud)
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);
}
}
Run Code Online (Sandbox Code Playgroud)