Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

days between two dates compare -> 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?

like image 306
eav Avatar asked Dec 01 '22 02:12

eav


2 Answers

You can use the JodaTime API as shown here.

like image 127
npinti Avatar answered Dec 04 '22 11:12

npinti


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!

like image 24
user and Avatar answered Dec 04 '22 09:12

user and