[英]How to check if the difference between 2 dates is more than 20 minutes
I have a datetime in a variable previous
. 我
previous
的变量中有一个日期时间。 Now i want to check if the previous datetime is more than twenty minutes before the current time. 现在我想检查前一个日期时间是否超过当前时间之前的二十分钟。
Date previous = myobj.getPreviousDate();
Date now = new Date();
//check if previous was before 20 minutes from now ie now-previous >=20
How can we do it? 我们怎么做?
Use 使用
if (now.getTime() - previous.getTime() >= 20*60*1000) {
...
}
Or, more verbose, but perhaps slightly easier to read: 或者,更详细,但也许更容易阅读:
import static java.util.concurrent.TimeUnit.*;
...
long MAX_DURATION = MILLISECONDS.convert(20, MINUTES);
long duration = now.getTime() - previous.getTime();
if (duration >= MAX_DURATION) {
...
}
You should really use Calendar object instead of Date: 您应该使用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
}
Java 8 solution: 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);
}
}
Get the times in milliseconds, and check the difference: 以毫秒为单位获取时间,并检查差异:
long diff = now.getTime() - previous.getTime();
if (diff > 20L * 60 * 1000) {
// ...
}
Another solution could be to use Joda time. 另一种解决方案可能是使用Joda时间。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.