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 ?
You're crossing a daylight saving time boundary, hence the 1 hour difference.
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.
(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) */
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With