Why the difference between two dates doesn't give me an integer number of days
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 am I not getting a whole few days? How do I calculate the difference between two dates?
Many thanks.
a source to share
Your first date will come out as GMT -0800, the second as GMT-077, which is 1 hour difference, which is 0.041666 times a day - exactly what you choose.
This may be due to daylight saving time differences, since one of your dates is in January and the other is in June; thus, one could save on daylight, and another from it. (And GMT -0800 is PST if not in daylight, and GMT -0700 is PST when in daylight.)
You should be safe to simply round to the nearest whole number of days, as daily savings will never change by more than an hour in either direction.
a source to share
This should get an integer number of days between dates, even if there is a daylight difference (or just the time zone) and there is no dreaded rounding off. Rounding is scary for me because it takes an answer I don't like and wiggles it while it calculates exactly what I wanted to calculate.
// assuming this date and the other date are date only
Date.prototype.daysSince = function(other) {
// get the timezone difference between then and now (in minutes)
var dstDiff = other.getTimezoneOffset() - this.getTimezoneOffset();
// convert the timezone different to milliseconds
var dstDiffMs = dstDiff * 60 * 100;
// get the milliseconds difference between the two dates
var diff = this.valueOf() - other.valueOf() + dstDiffMs;
// convert to days
var days = diff / 86400000; // or 60*60*24*1000 if you prefer
return days;
};
a source to share
Javascript does not do floating point math as one would expect. It's not smart enough to round up to what you want to see. For a simple fix do
Math.ceil((thru - from) / (1000 * 24 * 60 * 60))
Second, there will be a difference in milliseconds between the dates. You can normalize using
thru.setHours(0,0,0,0);
and
from.setHours(0,0,0,0);
before using them
a source to share