Wednesday, December 26, 2007

Confusion

On two occasions I have been asked, – "Pray, Mr. Babbage, if you put into the machine wrong figures, will the right answers come out?" In one case a member of the Upper, and in the other a member of the Lower, House put this question. I am not able rightly to apprehend the kind of confusion of ideas that could provoke such a question.

-- Charles Babbage, English mathematician, philosopher, and mechanical engineer

 

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)