Взяли качели, основываясь на ответе @ Ройи:
/**
* Translates seconds into human readable format of seconds, minutes, hours, days, and years
*
* @param {number} seconds The number of seconds to be processed
* @return {string} The phrase describing the the amount of time
*/
function forHumans ( seconds ) {
var levels = [
[Math.floor(seconds / 31536000), 'years'],
[Math.floor((seconds % 31536000) / 86400), 'days'],
[Math.floor(((seconds % 31536000) % 86400) / 3600), 'hours'],
[Math.floor((((seconds % 31536000) % 86400) % 3600) / 60), 'minutes'],
[(((seconds % 31536000) % 86400) % 3600) % 60, 'seconds'],
];
var returntext = '';
for (var i = 0, max = levels.length; i < max; i++) {
if ( levels[i][0] === 0 ) continue;
returntext += ' ' + levels[i][0] + ' ' + (levels[i][0] === 1 ? levels[i][1].substr(0, levels[i][1].length-1): levels[i][1]);
};
return returntext.trim();
}
Приятно, что у меня нет повторяющихся if
с, и они не дадут вам 0 лет 0 дней 30 минут 1 секунду , например.
Например:
forHumans(60)
выходы 1 minute
forHumans(3600)
выходы 1 hour
и forHumans(13559879)
выходы 156 days 22 hours 37 minutes 59 seconds