开发者

javascript date difference

I've looked at: Get difference between 2 dates in javascript?

And I still can't get this to work.

var difference = data.List[0].EndDate - Math.round(new Date().getTime()/1000.0) * 1000;
var daysRemaining = Math.floor(difference / 1000 / 60 / 60 / 24);
var hoursRemaining = Math.floor(difference / 1000 / 60 / 60 - (24 * daysRemaining));
var minutesRemaining = Math.floor(difference / 1000 / 60 - (24 * 60 * daysRemaining) - (60 * hoursRemaining));
var secondsRemaining = Math.floor(difference / 1000 - (24 * 60 *开发者_如何学编程 60 * daysRemaining) - (60 * 60 * hoursRemaining) - (60 * minutesRemaining));

data.List[0].EndDate is a UTC number (like: 1291427809310 (http://www.epochconverter.com/)) that will always be later than the current date.


function days_between(date1, date2) {

    // The number of milliseconds in one day
    var ONE_DAY = 1000 * 60 * 60 * 24

    // Convert both dates to milliseconds
    var date1_ms = date1.getTime()
    var date2_ms = date2.getTime()

    // Calculate the difference in milliseconds
    var difference_ms = Math.abs(date1_ms - date2_ms)

    // Convert back to days and return
    return Math.round(difference_ms/ONE_DAY)

}

http://www.mcfedries.com/javascript/daysbetween.asp


I now believe this is the best solution:

http://momentjs.com/


You say that UTC timestamp is "2004-09-16T23:59:58.75"?

So you are basically doing

var x = "2004-09-16T23:59:58.75" - 123456

Now that you clarified that, than the above does not apply. You new issue is the number of milliseconds is in the past so when you do the difference calculation, you are getting a negative number. You probably want to swap the order around.

var difference = new Date().getTime()-data.List[0].EndDate;


If EndDate is in milliseconds, and getTime() returns milliseconds, why do you divide it by 1000 only to multiply it by 1000 in the same line? And if you only need second precision for all the rest of the code, why work in milliseconds? Start out with a number of seconds to simplify all your calculations:

var difference = Math.round((data.List[0].EndDate - new Date().getTime()) / 1000);
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜