Вручную это немного многословно, но, конечно, это можно сделать:
function formatDuration(seconds) {
let years = Math.floor(seconds / (3600 * 24 * 365));
seconds -= years * 3600 * 24 * 365;
let days = Math.floor(seconds / (3600 * 24));
seconds -= days * 3600 * 24;
let hrs = Math.floor(seconds / 3600);
seconds -= hrs * 3600;
let minutes = Math.floor(seconds / 60);
seconds -= minutes * 60;
let result = '';
// Format the string based on the various time frames
if (years > 0) {
if (years == 1)
result += years + ' year,';
else
result += years + ' years,';
}
if (days > 0) {
if (days == 1)
result += days + ' day,';
else
result += days + ' days,';
}
if (hrs > 0) {
if (hrs == 1)
result += hrs + ' hour,';
else
result += hrs + ' hours,';
}
if (minutes > 0) {
if (minutes == 1)
result += minutes + ' minute,';
else
result += minutes + ' minutes,';
}
if (seconds > 0) {
if (seconds == 1)
result += seconds + ' second,';
else
result += seconds + ' seconds,';
}
// Remove the comma at the end
result = result.slice(0, result.length - 1);
// find the index of the last comma
let n = result.lastIndexOf(',');
// Divide the string where the comma was and substitute with an and
result = result.slice(0, n) + result.slice(n).replace(',', ' and ');
return result;
}
console.log(formatDuration(3662)); // 1 hour, 1 minute and 2 second
console.log(formatDuration(62)); // 1 minute and 2 second
console.log(formatDuration(94608000)); // 3 years
Предлагаю воспользоваться библиотекой времени, посмотрите Moment.js - один из лучших