Recently a needed to get the number of days between two dates in Java.
Easy, right? Quite a few pages & articles suggest, and I admit my first iteration too, was:
Calendar firstDay = new GregorianCalendar(2006, Calendar.FEBRUARY, 3)
Calendar lastDay = new GregorianCalendar(2006, Calendar.JULY, 17);
static final long DAY_MS = 1000 * 60 * 60 * 24;
int days = (lastDay.getTime().getTime() - firstDay.getTime().getTime()) / DAY_MS;
It turns out this is WRONG, for example for the two dates given (days == 163, but shold be 164!) - some rounding error. This will round correctly, as some better Web pages explain:
double daysDouble = lastLong - firstLong;
int days = (int) Math.round(daysDouble / DAY_MS); // = 164
but using the Calendar API provides a clearer, more reable and most importantly correct version, too:
assert firstDay.get(Calendar.YEAR) == lastDay.get(Calendar.YEAR); // Assumption
int days = lastDay.get(Calendar.DAY_OF_YEAR) - firstDay.get(Calendar.DAY_OF_YEAR);
Or, for more calculations of this kind, consider http://joda-time.sourceforge.net/
Easy, right? Quite a few pages & articles suggest, and I admit my first iteration too, was:
Calendar firstDay = new GregorianCalendar(2006, Calendar.FEBRUARY, 3)
Calendar lastDay = new GregorianCalendar(2006, Calendar.JULY, 17);
static final long DAY_MS = 1000 * 60 * 60 * 24;
int days = (lastDay.getTime().getTime() - firstDay.getTime().getTime()) / DAY_MS;
It turns out this is WRONG, for example for the two dates given (days == 163, but shold be 164!) - some rounding error. This will round correctly, as some better Web pages explain:
double daysDouble = lastLong - firstLong;
int days = (int) Math.round(daysDouble / DAY_MS); // = 164
but using the Calendar API provides a clearer, more reable and most importantly correct version, too:
assert firstDay.get(Calendar.YEAR) == lastDay.get(Calendar.YEAR); // Assumption
int days = lastDay.get(Calendar.DAY_OF_YEAR) - firstDay.get(Calendar.DAY_OF_YEAR);
Or, for more calculations of this kind, consider http://joda-time.sourceforge.net/