Thursday 5 June 2008

Simple code for finding the number of whole days between two Java Calendars

So... here's a bit of code I've written that should calculate the number of whole days between tw0 Java calendars. Unit testing comes up perfectly, showing that it takes account of TimeZones and all that tom-foolery that I can think of with Java Calendar.

Of course, this wouldn't ever happen if you used Joda-Time, but not all of us are that lucky!

/**
* Returns the number of days between the start and end of the period. Partial days are discarded. Time zone information accounted for, so be careful
*
* @return The number of whole days between the two as a positive integer.
*/
public Integer differenceInDays() {
long start = period.getStart().getTimeInMillis();
long end = period.getEnd().getTimeInMillis();
long difference = Math.abs(end - start);
return new Integer((int) (difference / DateUtils.MILLIS_PER_DAY));
}
(DateUtils.MILLIS_PER_DAY is a constant, which is actually a long of size 86400000)