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?
You can use the JodaTime API as shown here.
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With