Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
895 views
Welcome To Ask or Share your Answers For Others

1 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...