tags:

views:

71

answers:

2

Hi,

Can someone explain this to me. From jconsole ...

from = new Date('01/01/2010')
Fri Jan 01 2010 00:00:00 GMT-0800 (PST)

thru = new Date('06/07/2010')
Mon Jun 07 2010 00:00:00 GMT-0700 (PST)

(thru - from) / (1000 * 24 * 60 * 60)
156.95833333333334

Why don't I get a whole number of days? How do I calculate the difference between two dates?

thanks much.

A: 

Javascript does not do floating point math the way one would expect. It is not clever enough to round up to what you want to see. For a simple fix do

Math.ceil((thru - from) / (1000 * 24 * 60 * 60))

Secondly, there will be a difference in milliseconds between the dates. You can normalise using

thru.setHours(0,0,0,0);

and

from.setHours(0,0,0,0);

before using them

mplungjan
Ahem - Math.ceil seems to be better than Math.round - sorryAlso there is the matter of DST I did not notice you crossed
mplungjan
+10  A: 

Your first date is coming out as GMT -0800, the second is GMT -0700 - that's a 1 hour difference, which is 0.041666 of a day - exactly the amount you're off by.

This may have to do with daylight savings time differences, since one of your dates is in January and the other is in June; thus one would be on daylight savings and the other would be off it. (And GMT -0800 is PST when not on daylight savings; GMT -0700 is PST when on daylight savings.)

You should be safe to simply round to the nearest integral number of days, since daylight savings will never vary by more than an hour in either direction.

Amber
thanks for the explanation. Math.ceil should work
You probably want to actually round, since if the daylight savings difference were going the other way (Jun to Jan, instead of Jan to Jun), you'd actually be a bit above the target number.
Amber
No. When we adjust the clock up by an hour (GMT -0700) Math.ceil rounds it upwards. When we adjust the clock back by an hour (GMT -0800), Math.ceil would have no effect.
When the clock goes back by an hour, you'll get a result which is 0.041666 above an integer (say, 156.041666). `ceil` will take that up to to 157, as opposed to 156 which would be the correct number.
Amber
yes your are right