Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript Date difference bug?

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 ?

like image 299
disc0dancer Avatar asked Mar 05 '10 14:03

disc0dancer


3 Answers

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

like image 116
Martin Avatar answered Sep 20 '22 03:09

Martin


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.

like image 39
Jay Avatar answered Sep 19 '22 03:09

Jay


(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) */

like image 27
kennebec Avatar answered Sep 19 '22 03:09

kennebec