Format Duration - Js

Author - Format Duration - JS
Cristian
August 28th, 2020
Format Duration - JS

Format Duration - JS

It returns the human-readable format of the given number of milliseconds.

We divide "milliSeconds" with the appropriate values to obtain the appropriate values for day, hour, minute, second and millisecond. We use Object.entries() with Array.prototype.filter() to keep only non-zero values. We use Array.prototype.map() to create the string for each value. We use String.prototype.join(', ') to combine the values into a string.

HTML

<h1 id="display"></h1>

JavaScript

const duration = miliSeconds => {
  if (miliSeconds < 0) miliSeconds = -miliSeconds;
  const timeArray = {
    day: Math.floor(miliSeconds / 86400000),
    hour: Math.floor(miliSeconds / 3600000) % 24,
    minute: Math.floor(miliSeconds / 60000) % 60,
    second: Math.floor(miliSeconds / 1000) % 60,
    millisecond: Math.floor(miliSeconds) % 1000
  };
  
  const string = Object.entries(timeArray)
    .filter(val => val[1] !== 0)
    .map(([key, val]) => `${val} ${key}${val !== 1 ? 's' : ''}`)
    .join(', ');
  
  return string;
};
document.querySelector('#display').innerHTML = duration(43275055704);
CodePen Link: https://codepen.io/criscond/pen/WNwONmE