> easier way?

hi i'm asking myself if there is an easier way to get the number of days between two dates.

I want only the days, without looking at the hours or minutes.

Therefore if today is monday, and the date wich i want to compare is on wednesday, the days between are 2 (the time does not matter)

Therefore i use this code:

        Calendar c = Calendar.getInstance();
        // Only the day:
        c.set(Calendar.HOUR, 0);
        c.set(Calendar.MINUTE, 0);
        c.set(Calendar.SECOND, 0);
        c.set(Calendar.MILLISECOND, 0);

        Calendar to = Calendar.getInstance();
        to.setTime(date);
        to.set(Calendar.HOUR, 0);
        to.set(Calendar.MINUTE, 0);
        to.set(Calendar.SECOND, 0);
        to.set(Calendar.MILLISECOND, 0);
        date = to.getTime();

        long millsPerDay = 1000 * 60 * 60 * 24;

        long dayDiff = ( date.getTime() - dateToday.getTime() ) / millsPerDay;

after this code i have the days in a long called dayDiff. but is it really necessarily to make a calendar of the date, set the time to 00:00:00:00 and save to.getTime() in date ?

Edit: After using joda-time : Is it also possible with joda-time to get information about the days, like: difference==1 ==> Tomorrow, or difference == -1 ==> yesterday or do I have to do that manually?


您可以使用JodaTime API,如下所示。


For specified task I always use this convenient way: (no lib, just Java 5 API)

import java.util.concurrent.TimeUnit;

Date d1 = ...
Date d2 = ...

long daysBetween = TimeUnit.MILLISECONDS.toDays(d2.getTime() - d1.getTime());

Enjoy!


public long dayDiff(Date d1, Date d2) {
    final long DAY_MILLIS = 1000 * 60 * 60 * 24;
    long day1 = d1.getTime() / DAY_MILLIS;
    long day2 = d2.getTime() / DAY_MILLIS;
    return (day1 - day2);
}

对不起,我的疏忽

链接地址: http://www.djcxy.com/p/36666.html

上一篇: 在java中查找两个(Joda Time)DateTime对象之间的确切区别

下一篇: >更简单的方法?