Created
May 16, 2014 12:12
-
-
Save IrakliJani/7337a177750865221a84 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function formatDuration (seconds) { | |
return [60, 3600, 86400, 31536000] | |
.reduceRight(function (results, current) { | |
var seconds = results.pop(); | |
results.push(Math.floor(seconds / current)); | |
results.push(seconds - results[results.length - 1] * current); | |
return results; | |
}, [seconds]) | |
.map(function (value, index) { | |
var words = ['year', 'day', 'hour', 'minute', 'second']; | |
return value ? value + ' ' + words[index] + (value == 1 ? '' : 's') : 0; | |
}) | |
.filter(Boolean) | |
.join(', ') | |
.replace(/,([^,]*)$/, ' and$1') || 'now'; | |
} | |
console.log(formatDuration(0)); // => now | |
console.log(formatDuration(60)); // => 1 minute | |
console.log(formatDuration(61)); // => 1 minute and 1 second | |
console.log(formatDuration(62)); // => 1 minute and 2 seconds | |
console.log(formatDuration(3662)); // => 1 hour, 1 minute and 2 seconds | |
console.log(formatDuration(366212345)); // => 11 years, 223 days, 13 hours, 39 minutes and 5 seconds |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment