Created
January 22, 2015 18:36
-
-
Save nramirez/3802b889ecd99ff3e1db to your computer and use it in GitHub Desktop.
Human readable duration format
This file contains hidden or 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
var formatDuration = function(duration){ | |
var result = '', | |
tempTime =0, | |
durations = [ | |
{ description : 'year', plural: "years", range : 31536000 }, | |
{ description : 'day', plural: "days", range : 86400 }, | |
{ description : 'hour', plural: "hours", range : 3600 }, | |
{ description : 'minute', plural: "minutes", range : 60 }, | |
{ description : 'second', plural: "seconds", range : 1 } | |
]; | |
if (duration === 0) | |
{ return 'now';}; | |
result = durations.reduce(function(prev, current){ | |
if (duration >= current.range) { | |
tempTime = parseInt(duration/current.range); | |
duration -= (tempTime *current.range); | |
prev += ' ' + tempTime + ' ' + (tempTime > 1 ? current.plural : current.description) + ','; | |
}; | |
return prev; | |
},0); | |
result = result.slice(2, result.length -1); //Ignore the first two position and pop the last , | |
//Check if more than one , were inserted, then we need to | |
//replace the last one for a 'and' | |
if (result.split(',').length > 1) { | |
var lastComma = result.lastIndexOf(','); | |
result = result.slice(0,lastComma) + ' and' + result.slice(lastComma+1); | |
}; | |
return result; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment