views:

206

answers:

3

Edit: It's not a bug as Martin pointed out. I'm just crossing the daylight saving time, hence the 1h difference.

I want to calculate the difference in days between "Mar 29 2010" and "Mar 09 2010" so i have the following code:

((new Date(2010, 2, 29)).getTime() - (new Date(2010, 2, 8)).getTime()) / 86400000

86400000 is the number of milliseconds in a day and the difference between the dates is returned in milliseconds, so this should work. Only it doesn't quite. I get

20.958333333333332

It's the difference between those 2 dates that is wrong. It's supposed to be 1814400000 (21 days times 86400000 ), but it actually is 1810800000.

Moreover if I change the difference to:

((new Date(2010, 2, 28)).getTime() - (new Date(2010, 2, 7)).getTime()) / 86400000

the same difference, only shifted one day back, i get normal results.

This happens only if we try to get (x-y) where x is after March 29 2010 and y is before March 29 2010.

I get this on Safari 4 and Firefox 3.6 on Mac, as well as IE 8 on windows 7. Haven't tried other browsers.

Am I doing something wrong or is this a known bug ?

+11  A: 

You're crossing a daylight saving time boundary, hence the 1 hour difference.

Martin
Yes, you're right :) I added 3,600,000 to the date difference and the division turned out correctly. Silly of me to let this slip.
Discodancer
DST is on March 14th this year in the US. It is included in both ranges isn't it?
Eric Bréchemier
I'm in Macedonia, so it's different on my machine i guess.
Discodancer
DST should be on March 28 at 1am in Macedonia... That makes sense then.
Eric Bréchemier
+1  A: 

Daylight Savings Time makes date arithmetic a tricky thing. It means that while 363 days each year are 24 hours long, one day is 25 hours and one day is only 23 hours. Personally I vote for abolishing daylight savings time.

In Java, there's a GregorianCalendar class that does date arithmetic correctly despite DST. I guess that doesn't help much in Javascript.

Jay
+2  A: 

(I see you caught the dst change)

Any javascript division is liable to have floating point problems- set the 'accuracy' you need.

You don't need to get the time yourself- javascript will do the conversion for you.

+((new Date(2010, 2, 29) - new Date(2010, 2, 8))/ 86400000).toFixed(2)

/* returned value: (Number) 20.96 (local time. which may be what you want- otherwise, set the UTC date parts) */

kennebec
I could also use Math.round() on the result since the 1h difference will never be enough to give you errors in rounding. I wonder which one is faster ?
Discodancer