开发者

Why doesn't the difference between two dates give me a whole 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 don't I g开发者_如何学JAVAet a whole number of days? How do I calculate the difference between two dates?

thanks much.


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.


This should get the whole number of days between the dates even if there are daylight savings (or just timezone) differences, and there's no scary rounding. Rounding is scary to me because it's taking an answer I don't like and fudging it, whereas this calculates exactly what I meant 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;
};


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜