检查Date对象是否在过去24小时内发生

时间:2014-07-14 20:19:16

标签: java date calendar

我正在尝试将时间与24小时前的时间进行比较。

这就是我所拥有的:

public boolean inLastDay(Date aDate) {

    Calendar cal = Calendar.getInstance();
    cal.add(Calendar.DAY_OF_MONTH, -1);
    Date pastDay = cal.getTime();

    if(aDate!= null) {
        if(aDate.after(pastDay)){
            return true;
        } else {
            return false;
        }
    } else {
        return false;
    }
}

输入示例(这些从字符串转换为日期):

null (this would return false)
Jul 11 at 19:36:47 (this would return false)
Jul 14 at 19:40:20 (this would return true)

这似乎不起作用。它总是返回false。任何帮助将不胜感激!

答案:最后我不断变得虚假,因为“aDate”没有毫秒,年和“pastDay”所做的其他值。

为了解决这个问题,我做了以下几点:

SimpleDateFormat sdfStats = new SimpleDateFormat("MMM dd 'at' HH:mm:ss");
Calendar cal = Calendar.getInstance();
cal.add(Calendar.HOUR, -24);
Date yesterdayUF = cal.getTime();
String formatted = sdfStats.format(yesterdayUF);
Date yesterday = null;

    try {
        yesterday = sdfStats.parse(formatted);
    } catch (Exception e) {

    }

    if(aDate!= null) {
        if(aDate.after(yesterday)){
            return true;
        } else {
            return false;
        }
    } else {
        return false;
    }

2 个答案:

答案 0 :(得分:5)

如何使用数学?

static final long DAY = 24 * 60 * 60 * 1000;
public boolean inLastDay(Date aDate) {
    return aDate.getTime() > System.currentTimeMillis() - DAY;
}

答案 1 :(得分:1)

所以我测试了这个并且它工作了(随意删除调试的东西) 确保您使用的是DateFormat。

public static boolean inLastDay(java.util.Date aDate) {
    java.util.Date today = DateFormat.getDateTimeInstance().getCalendar().getTime();

    java.util.Date twentyfourhoursbefore = DateFormat.getDateTimeInstance().getCalendar().getTime();
    twentyfourhoursbefore.setTime(twentyfourhoursbefore.getTime() - (24*60*60*1000));

    System.out.println(DateFormat.getDateTimeInstance().format(today));
    System.out.println(DateFormat.getDateTimeInstance().format(twentyfourhoursbefore));
    System.out.println(DateFormat.getDateTimeInstance().format(aDate));
    if(aDate.after(twentyfourhoursbefore) && aDate.before(today)){
        return true;
    }

    return false;
}

这是输出:

Using a time within 24 hours:
14.07.1934 22:44:46
13.07.1934 22:44:46
13.07.1934 23:44:46
true

Using a time EXACTLY 24 hours before (it should also work with more than 24 hours):
14.07.1934 22:47:12
13.07.1934 22:47:12
13.07.1934 22:47:12
false

Using a time 24 hours after ATM:
14.07.1934 22:48:20
13.07.1934 22:48:20
15.07.1934 22:48:20
false