williamparry
williamparry

Reputation: 488

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.

Upvotes: 8

Views: 23307

Answers (4)

user736893
user736893

Reputation:

I now believe this is the best solution:

http://momentjs.com/

Upvotes: 6

user736893
user736893

Reputation:

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

Upvotes: 11

epascarello
epascarello

Reputation: 207501

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;

Upvotes: 5

Dan Grossman
Dan Grossman

Reputation: 52372

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);

Upvotes: 3

Related Questions