【问题标题】:How to check if the difference between 2 dates is more than 20 minutes如何检查2个日期之间的差异是否超过20分钟
【发布时间】:2011-08-16 14:42:05
【问题描述】:

我在变量previous 中有一个日期时间。现在我想检查以前的日期时间是否比当前时间早二十分钟。

Date previous = myobj.getPreviousDate();

Date now = new Date();

//check if previous was before 20 minutes from now ie now-previous >=20

我们该怎么做?

【问题讨论】:

标签: java date


【解决方案1】:

使用

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) {
    ...
}

【讨论】:

  • @all:isnt if now.getTime -previous.getTime > 20*60*1000.我想检查从现在开始的时间是否超过 20 分钟
  • 对,如果“现在减去上一个”大于 20 分钟,那么上一个发生在 20 多分钟前。
  • 这在 2 次与夏令时切换点重叠时不起作用。
【解决方案2】:

使用Joda Time

boolean result = Minutes.minutesBetween(new DateTime(previous), new DateTime())
                        .isGreaterThan(Minutes.minutes(20));

【讨论】:

    【解决方案3】:

    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);
        }
    }
    

    【讨论】:

    • 在 Java 6 和 7 中也适用于 ThreeTen-Backport 项目,在 Android 中也适用于 ThreeTenABP 项目。
    【解决方案4】:

    你真的应该使用 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
    }
    

    【讨论】:

    • 应该是long diff = now.getTimeInMillis() - previous.getTimeInMillis();
    • 这在 2 次与夏令时切换点重叠时不起作用。
    • 要忽略节电点,您需要使用 UTC 时间。或者如果你很幸运,运行应用程序的国家/地区没有夏令时切换点(例如中国)
    【解决方案5】:

    以毫秒为单位获取时间,并检查差异:

    long diff = now.getTime() - previous.getTime();
    if (diff > 20L * 60 * 1000) {
        // ...
    }
    

    另一种解决方案可能是使用 Joda 时间。

    【讨论】:

    • OP 要求检查 previuos 是否在距离 now 20 分钟之前,而不是它们之间的差异
    • @Eng:读得快。更正:)
    • 是反方向使用的比较符号。我想检查以前的时间是否比当前时间过去 20 分钟以上
    • @Akshay:比较符号很好。减法方向错误(现已更正)。但是如果previousnow早20分钟,则时差会大于20分钟。
    猜你喜欢
    • 1970-01-01
    • 2011-12-03
    • 2011-01-24
    • 1970-01-01
    • 1970-01-01
    • 2020-03-06
    • 1970-01-01
    • 1970-01-01
    • 2014-06-12
    相关资源
    最近更新 更多