Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
24
rated 0 times [  26] [ 2]  / answers: 1 / hits: 154769  / 12 Years ago, sat, january 12, 2013, 12:00:00

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?


More From » date

 Answers
48

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




[#80913] Friday, January 11, 2013, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
daja

Total Points: 407
Total Questions: 103
Total Answers: 103

Location: Ghana
Member since Sun, Mar 27, 2022
2 Years ago
daja questions
Tue, Dec 21, 21, 00:00, 2 Years ago
Thu, Apr 23, 20, 00:00, 4 Years ago
Fri, Sep 6, 19, 00:00, 5 Years ago
Tue, Jul 23, 19, 00:00, 5 Years ago
;