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

Nik*_*xx2 1 java calendar date

我想把时间与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;
    }
}
Run Code Online (Sandbox Code Playgroud)

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

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)
Run Code Online (Sandbox Code Playgroud)

这似乎不起作用.它总是返回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;
    }
Run Code Online (Sandbox Code Playgroud)

Pet*_*rey 6

用数学怎么样?

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

  • 注意:这不会注意到夏令时的变化.即一天有时23小时或25小时. (4认同)