Skip to content

Instantly share code, notes, and snippets.

@thykka
Created December 23, 2013 18:29
Show Gist options
  • Save thykka/8102188 to your computer and use it in GitHub Desktop.
Save thykka/8102188 to your computer and use it in GitHub Desktop.
function formatDuration (seconds) {
var ans = [], last, sec = seconds, min = 0, hrs = 0, dys = 0, yrs = 0;
if(sec === 0) { return "now"; }
while (sec >= 60 * 60 * 24 * 365) { yrs++; sec -= 60 * 60 * 24 * 365; }
while (sec >= 60 * 60 * 24) { dys++; sec -= 60 * 60 * 24; }
while (sec >= 60 * 60) { hrs++; sec -= 60 * 60; }
while (sec >= 60) { min++; sec -= 60; }
if(yrs >= 1) {ans.push( yrs > 1 ? yrs + " years" : "1 year" );}
if(dys >= 1) {ans.push( dys > 1 ? dys + " days" : "1 day" );}
if(hrs >= 1) {ans.push( hrs > 1 ? hrs + " hours" : "1 hour" );}
if(min >= 1) {ans.push( min > 1 ? min + " minutes": "1 minute");}
if(sec >= 1) {ans.push( sec > 1 ? sec + " seconds": "1 second");}
last = ans.pop();
ans = ans.length >= 1 ? ans.join(", ") + " and " + last : last;
return ans;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment