Saturday, December 22, 2007

Calculate Difference in Days

Java has no built-in "give me the difference in days" API methods. One commonly-suggested solution is to get the difference in milliseconds between two dates and, using the number of milliseconds in a day, determine the number of days. Unfortunately, daylight savings time creates some problems with this method, as the following Groovy script demonstrates:
#! /usr/bin/groovy

df = new java.text.SimpleDateFormat('yyyy-MM-dd')

// These dates cross DST...
startDate = df.parse('2007-03-10')
endDate = df.parse('2007-03-12')

expectedDifferenceInDays = 2

// Here's the problem with millis:
millisInADay = 1000 * 60 * 60 * 24
differenceInMillis = endDate.time - startDate.time
actualDifferenceInDays = differenceInMillis / millisInADay

assert expectedDifferenceInDays != actualDifferenceInDays
assert actualDifferenceInDays < expectedDifferenceInDays


Here's a more straightforward solution using Java's Calendar API:
#! /usr/bin/groovy

df = new java.text.SimpleDateFormat('yyyy-MM-dd')

// These dates cross DST...
startDate = df.parse('2007-03-10')
endDate = df.parse('2007-03-12')

expectedDifferenceInDays = 2

calendar = Calendar.instance
calendar.time = startDate
actualDifferenceInDays = 0
while (calendar.time.before(endDate)) {
actualDifferenceInDays++
calendar.add(Calendar.DATE, 1)
}
assert expectedDifferenceInDays == actualDifferenceInDays


Note that what constitutes "a day" is subject to interpretation... :o)

No comments:

Post a Comment