说我有两个日期字段receiveDate和currentDate。我想检查receiveDate是否在currentDate之前5天。我所做的是将日期转换为毫秒,然后与5进行比较。是否有更好的方法?如果是这样,我的方式和原因会更好吗?谢谢。

我写的方法-

private static final double DAY_IN_MILLISECONDS = 86400000;

// Param date is the receivedDate
private long getDaysOld(final Date date) {


    Calendar suppliedDate = Calendar.getInstance();
    suppliedDate.setTime(date);
    Calendar today = Calendar.getInstance();
    today.setTime(currentDate);

    double ageInMillis = (today.getTimeInMillis() - suppliedDate.getTimeInMillis());
    double tempDouble;

    if(isEqual(ageInMillis, 0.00) || isGreaterThan(Math.abs(ageInMillis), DAY_IN_MILLISECONDS)) {
        tempDouble =  ageInMillis / DAY_IN_MILLISECONDS;
    } else {
        tempDouble =  DAY_IN_MILLISECONDS / ageInMillis;
    }

    long ageInDays = Math.round(tempDouble);

    return ageInDays;


}

然后我有类似的东西-
long daysOld = getDaysOld(receivedDate) ;
if(daysOld <= 5) {
    .... some business code ....
}

最佳答案

它可以大大缩短:

int daysOld = (System.currentTimeMillis() - date.getTime()) / DAY_IN_MILLISECONDS;

09-30 21:03