Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 619
williamparry Avatar asked Dec 14 '10 03:12

williamparry


People also ask

Can you subtract dates JavaScript?

To subtract days from a JavaScript Date object, you need to: Call the getDate() method to get the day of the Date object. Subtract the number of days you want from the getDate() returned value. Call the setDate() method to set the day of the Date object.

How do you use date difference function?

To calculate the number of days between date1 and date2, you can use either Day of year ("y") or Day ("d"). When interval is Weekday ("w"), DateDiff returns the number of weeks between the two dates. If date1 falls on a Monday, DateDiff counts the number of Mondays until date2. It counts date2 but not date1.


2 Answers

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

like image 84
THE JOATMON Avatar answered Oct 01 '22 15:10

THE JOATMON


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;
like image 35
epascarello Avatar answered Oct 01 '22 14:10

epascarello