I'm calculating the difference between 2 dates for which there are many differing examples available. The time returned is in milliseconds so I need to convert it into something more useful.
Most examples are for days:hours:minutes:seconds or hours:minutes, but I need days:hours:minutes so the seconds should be rounded up into the minutes.
The method I'm currently using gets close but shows 3 days as 2.23.60 when it should show 3.00.00 so something is not quite right. As I just grabbed the current code from an example on the web, I'm open to suggestions for other ways of doing this.
I'm obtaining the time in milliseconds by subtracting a start date from an end date as follows:-
date1 = new Date(startDateTime);
date2 = new Date(endDateTime);
ms = Math.abs(date1 - date2)
I basically need to take the ms variable and turn in into days.hours:minutes.
Something like this?
function dhm(t){
var cd = 24 * 60 * 60 * 1000,
ch = 60 * 60 * 1000,
d = Math.floor(t / cd),
h = Math.floor( (t - d * cd) / ch),
m = Math.round( (t - d * cd - h * ch) / 60000),
pad = function(n){ return n < 10 ? '0' + n : n; };
if( m === 60 ){
h++;
m = 0;
}
if( h === 24 ){
d++;
h = 0;
}
return [d, pad(h), pad(m)].join(':');
}
console.log( dhm( 3 * 24 * 60 * 60 * 1000 ) );
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With