Skip to content

Instantly share code, notes, and snippets.

@betamos
Last active August 6, 2020 20:50
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save betamos/6306412 to your computer and use it in GitHub Desktop.
Save betamos/6306412 to your computer and use it in GitHub Desktop.
Tiny JS utility to print duration in a human readable fashion
/* Author: Didrik Nordström, didrik@betamos.se */
/**
* Format a duration in milliseconds to a human readable format, e.g.
* "4y 2d 3h 10m 10s 255ms". Negative durations are formatted like "- 8h 30s".
* Granularity is always ms.
*
* @param t Duration in milliseconds
* @return A formatted string containing the duration or "" if t=0
*/
var readableDuration = (function() {
// Each unit is an object with a suffix s and divisor d
var units = [
{s: 'ms', d: 1},
{s: 's', d: 1000},
{s: 'm', d: 60},
{s: 'h', d: 60},
{s: 'd', d: 24},
{s: 'y', d: 365} // final unit
];
// Closure function
return function(t) {
t = parseInt(t); // In order to use modulus
var trunc, n = Math.abs(t), i, out = []; // out: list of strings to concat
for (i = 0; i < units.length; i++) {
n = Math.floor(n / units[i].d); // Total number of this unit
// Truncate e.g. 26h to 2h using modulus with next unit divisor
trunc = (i+1 < units.length) ? n % units[i+1].d : n; // …if not final unit
trunc ? out.unshift(''+ trunc + units[i].s) : null; // Output if non-zero
}
(t < 0) ? out.unshift('-') : null; // Handle negative durations
return out.join(' ');
};
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment