Work with a time span in Javascript

Chris Dutrow picture Chris Dutrow · Jan 12, 2013 · Viewed 118.6k times · Source

Using Date.js already, but can also use another library if necessary.

Not sure what is the best way to work with time deltas. Specifically, I want to display the time that has elapsed between now and a past date-time.

So I need to do something like this:

var elapsed_time = new Date() - pastDate;
pastDate.toString('days-hours-minutes-seconds');

Gotten it to mostly work using Date.js, but the problem is now I'm working with a Date object and not a timespan, so what should be an 23 hour time span is instead 23 hours after the Date's very first time:

var result = (new Date()) - past_date;
"result" is the number (probably milliseconds): 15452732
var result = (new Date() - past_date
"result" is a date from 1969: Wed Dec 31 1969 23:17:32

What I need is:

0 days 23 hours 17 minutes and 32 seconds

Any ideas?

Answer

Lee Taylor picture Lee Taylor · Jan 12, 2013

Sounds like you need moment.js

e.g.

moment().subtract('days', 6).calendar();

=> last Sunday at 8:23 PM

moment().startOf('hour').fromNow();

=> 26 minutes ago

Edit:

Pure JS date diff calculation:

var date1 = new Date("7/Nov/2012 20:30:00");
var date2 = new Date("20/Nov/2012 19:15:00");

var diff = date2.getTime() - date1.getTime();

var days = Math.floor(diff / (1000 * 60 * 60 * 24));
diff -=  days * (1000 * 60 * 60 * 24);

var hours = Math.floor(diff / (1000 * 60 * 60));
diff -= hours * (1000 * 60 * 60);

var mins = Math.floor(diff / (1000 * 60));
diff -= mins * (1000 * 60);

var seconds = Math.floor(diff / (1000));
diff -= seconds * (1000);

document.write(days + " days, " + hours + " hours, " + mins + " minutes, " + seconds + " seconds");