比较日期(以毫秒为单位)

时间:2010-10-26 16:41:01

标签: java datetime

假设我有两个日期字段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 ....
}

6 个答案:

答案 0 :(得分:2)

尝试joda-time。使用本机API进行时间计算总是很尴尬。 Joda时间使这种类型的计算更简单,并且也可以很好地处理时区。

答案 1 :(得分:2)

import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;


public class Test {

    private static long DAY_IN_MILLISECONDS = 24 * 60 * 60 * 1000;

    public static void main(String[] args) throws Exception {
        //
        Date currentDate = getGregorianDate(1990, Calendar.JANUARY, 20);
        Date receiveDate = getGregorianDate(1990, Calendar.JANUARY, 23);
        //
        if (getDifferenceBetweenDates(receiveDate, currentDate) < 5 * DAY_IN_MILLISECONDS) {
            System.out.println("Receive date is not so old.");
        }
        else {
            System.out.println("Receive date is very old.");
        }
    }

    private static long getDifferenceBetweenDates(Date date1, Date date2) {
        return Math.abs(date1.getTime() - date2.getTime());
    }

    private static Date getGregorianDate(int year, int month, int date) {
        Calendar calendar = GregorianCalendar.getInstance();
        calendar.set(year, month, date);
        return calendar.getTime();
    }

}

答案 2 :(得分:0)

它可以缩短很多:

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

答案 3 :(得分:0)

由于夏令时(一天可能有23或25小时),您不能简单地减去并除以24 * 60 * 60 * 1000。

例如,在英国,时钟在28/03/2010向前移动了一个小时。 27/03/2010和28/03/2010之间的差异为1天,但如果您遵循该方法,则会得到0。

您需要考虑偏移量:

public static long daysBetween(Date dateEarly, Date dateLater) {
    Calendar cal1 = Calendar.getInstance();
    cal1.setTime(dateEarly);  
    Calendar cal2 = Calendar.getInstance();
    cal2.setTime(dateLater);

    long endL = cal2.getTimeInMillis() + cal2.getTimeZone().getOffset( cal2.getTimeInMillis() );
    long startL = cal1.getTimeInMillis() + cal1.getTimeZone().getOffset( cal1.getTimeInMillis() );
    return (endL - startL) / (24 * 60 * 60 * 1000);
}

public static void main(String[] args) throws Exception {

    TimeZone.setDefault(TimeZone.getTimeZone("Europe/London"));  

    Date foo = new Date(2010,02,27);
    Date bar= new Date(2010,02,28);

    System.out.println(daysBetween(foo,bar)); //prints 1
}

答案 4 :(得分:0)

这完全取决于“五天”的含义。如果你星期一午餐时间收到一些东西,那么在星期六下午,你是否在五​​天内收到了它?经过的时间大于五天,但是您收到它的日期是五天前。想想你如何回答这个问题;现在关于你母亲如何回答这个问题。它可能不一样 - 我建议大多数人,特别是非程序员,计算当地中午的过去几天。星期三早上五点钟是星期二晚上十一点半之后的一天,即使它不到一天(不到四分之一天!)之后。

所以,我认为你想要做的只是比较日期,而不是时间。您可以通过将所有时间字段归零来使用Calendar执行此操作。鉴于到达日期和区域设置(所以你可以告诉我们午夜时间),我认为这是正确的:

    Calendar deadline = Calendar.getInstance(locale);
    deadline.set(Calendar.HOUR_OF_DAY, 0);
    deadline.set(Calendar.MINUTE, 0);
    deadline.set(Calendar.SECOND, 0);
    deadline.set(Calendar.MILLISECOND, 0);
    deadline.add(Calendar.DAY_OF_MONTH, 5);

    Calendar arrived = Calendar.getInstance(locale);
    arrived.setTime(arrivedDate);
    deadline.set(Calendar.HOUR_OF_DAY, 0);
    deadline.set(Calendar.MINUTE, 0);
    deadline.set(Calendar.SECOND, 0);
    deadline.set(Calendar.MILLISECOND, 0);

    boolean arrivedWithinDeadline = arrived.compareTo(deadline) <= 0;

你应该在实际使用之前彻底测试一下。

答案 5 :(得分:0)

以下是我的方法,它以天为单位返回确切的差异,

/**
 * method to get difference of days between current date and user selected date
 * @param selectedDateTime: your date n time
 * @param isLocalTimeStamp: defines whether the timestamp d is in local or UTC format
 * @return days
 */
public static long getDateDiff(long selectedDateTime, boolean isLocalTimeStamp)
{
    long timeOne = Calendar.getInstance().getTime().getTime();
    long timeTwo = selectedDateTime;
    if(!isLocalTimeStamp) 
        timeTwo += getLocalToUtcDelta();
    long delta = (timeOne - timeTwo) / ONE_DAY;

    if(delta == 0 || delta == 1) {
        Calendar cal1 = new GregorianCalendar();
        cal1.setTimeInMillis(timeOne);
        Calendar cal2 = new GregorianCalendar();
        cal2.setTimeInMillis(timeTwo);
        long dayDiff = cal1.get(Calendar.DAY_OF_MONTH) - cal2.get(Calendar.DAY_OF_MONTH);
        return dayDiff;
    }

    return delta;
}