Skip to content

Instantly share code, notes, and snippets.

@tigerclaw-az
Created December 16, 2013 22:40
Show Gist options
  • Save tigerclaw-az/7995758 to your computer and use it in GitHub Desktop.
Save tigerclaw-az/7995758 to your computer and use it in GitHub Desktop.
function formatDuration (seconds) {
// Complete this function
if (seconds === 0) return 'now';
var calc = {
years: {time: 60*60*24*365, str: 'year'},
days: {time: 60*60*24, str: 'day'},
hours: {time: 60*60, str: 'hour'},
mins: {time: 60, str: 'minute'}
}, duration = [];
for (var c in calc) {
var time = Math.floor(seconds / calc[c].time);
if (time > 0 && time !== calc[c].time) {
seconds -= time*calc[c].time;
duration.push(time + ' ' + calc[c].str + ((time > 1) ? 's' : ''));
}
}
if (seconds > 0) { duration.push(seconds + ' ' + 'second' + ((seconds > 1) ? 's' : '')); }
return duration.join(', ').replace(/,\s$/, '').replace(/,\s([^,]+)$/, ' and $1');
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment