开发者

Finding Date Difference

开发者 https://www.devze.com 2022-12-13 21:58 出处:网络
What\'s th开发者_运维知识库e efficient way of finding say if a date is 5 days earlier than another day? Do I need to parse both days using a particular SimpleDateFormat first before I compare?The best

What's th开发者_运维知识库e efficient way of finding say if a date is 5 days earlier than another day? Do I need to parse both days using a particular SimpleDateFormat first before I compare?


The best Java date time API is Joda Time. It makes these tasks, and others, much easier than using the standard API.


Most quickly, but least accurately, you might just put both into a java.util.Date, getTime() on both, and divide the difference by the number of milliseconds in a day.

You could make it a bit more accurate by creating two Calendar objects, and work with those.

If you really want to solve this well, and have a good bit of time on your hands, look at Joda Time.


The Calendar interface has some nice methods, including before, after, and equals.


http://www.java2s.com/Code/Java/Development-Class/DateDiffcomputethedifferencebetweentwodates.htm


You can do

Long DAY_IN_MILLIS = 86400000;

if((dateA - dateB) > DAY_IN_MILLIS * 5) {
    // dateA is more than 5 days older than dateB
}


Date date1 = // whatever
Date date2 = // whatever

Long fiveDaysInMilliseconds = 1000 * 60 * 60 * 24 * 5    
boolean moreThan5Days = Math.abs(date1.getTime() - date2.getTime()) > fiveDaysInMilliseconds 


If you need to ignore the time of the dates, you can do something like

    public static boolean compare5days(Date date, Date another) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(another);
        cal.add(Calendar.DATE, -5);

        // clear time 
        cal.set(Calendar.HOUR_OF_DAY, 0);
        cal.set(Calendar.MINUTE, 0);
        cal.set(Calendar.SECOND, 0);
        cal.set(Calendar.MILLISECOND, 0);

        return date.before(cal.getTime());
    }


days = (date2.getTime() - date1.getTime())/86400000L


days = (date2.getTime() - date1.getTime())

0

精彩评论

暂无评论...
验证码 换一张
取 消