#! /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