Skip to content

Instantly share code, notes, and snippets.

@betamos
Created August 22, 2013 12:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save betamos/6306791 to your computer and use it in GitHub Desktop.
Save betamos/6306791 to your computer and use it in GitHub Desktop.
Tweak from my other Gist, https://gist.github.com/betamos/6306412. Outputs seconds into "h+:mm:ss"
/* Author: Didrik Nordström, didrik@betamos.se */
/* Specifically for http://stackoverflow.com/questions/6312993 */
/**
* Format a duration in seconds to a human readable format using the notion
* "h+:mm:ss", e.g. "4:40:78". Negative durations are preceeded by "-".
*
* @param t Duration in seconds
* @return The formatted duration string
*/
var readableDuration = (function() {
// Each unit is an object with a suffix s and divisor d
var units = [
{s: '', d: 1}, // Seconds
{s: ':', d: 60}, // Minutes
{s: ':', d: 60}, // Hours
];
// 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
if (i+1 < units.length) // Tweak substr with two digits
trunc = ('00'+ n % units[i+1].d).substr(-2, 2); // …if not final unit
else
trunc = n;
out.unshift(''+ trunc + units[i].s); // Output
}
(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