1

I'm converting elapsed ms to HH:mm:ss, but if the elapsed ms are higher of a day, I lost that info:

const elapsedSeconds = 218509
const elapsed = moment.utc(elapsedSeconds * 1000).format('HH:mm:ss');
alert(elapsed); // print 12:41:49

How can I also display days from ms, near the HH:mm:ss? In this case there are 60hours, so it should print 2(days):12:41:49. Or 60:41:49 at least.

markzzz
  • 47,390
  • 120
  • 299
  • 507

1 Answers1

2

So based on your required ouput you can use moment library to convert date time to specified format.

For that your code looks like :

const elapsedMilliseconds = 218509000;
const duration = moment.duration(elapsedMilliseconds);
const elapsed = duration.days() + "(days):" + duration.hours() + ":" + duration.minutes() + ":" + duration.seconds();
alert(elapsed);

Result :

2(days):12:41:49

If you want to do by javascript to get total HH:mm:ss then :

function padTo2Digits(num) {
  return num.toString().padStart(2, '0');
}

function convertMsToHM(milliseconds) {
  let seconds = Math.floor(milliseconds / 1000);
  let minutes = Math.floor(seconds / 60);
  let hours = Math.floor(minutes / 60);

  seconds = seconds % 60;
  minutes = seconds >= 30 ? minutes + 1 : minutes;
  minutes = minutes % 60;

  return `${padTo2Digits(hours)}:${padTo2Digits(minutes)}:${padTo2Digits(seconds)}`;
}

console.log(convertMsToHM(218509000));

Result :

"60:42:49"
NIKUNJ PATEL
  • 2,034
  • 1
  • 7
  • 22