After consulting a few forums, I ended up using the code below to find the days difference. But, I see a problem with the logic (may be it\'s my over sight?). I see that for
1000 * 60 * 60 * 24
is wrong way to find day difference. You can use JodaTime but there is a pure java solution.
Let we have two inialized variables
Calendar firstDay = ...;
Calendar secondDay = ...;
and
firstDay.before(lastDay)
is true
.
Run
int firstDayNo = firstDay.get(Calendar.DAY_OF_YEAR);
int secondDayNo = secondDay.get(Calendar.DAY_OF_YEAR);
int dayDifference, yearMultiplier;
dayDifference = -firstDayNo;
yearMultiplier = secondDay.get(Calendar.YEAR) - firstDay.get(Calendar.YEAR);
while (yearMultiplier > 0) {
dayDifference += firstDay.getActualMaximum(Calendar.DAY_OF_YEAR);
firstDay.add(Calendar.YEAR, 1);
yearMultiplier--;
}
dayDifference += secondDayNo;
return dayDifference;