Javascript Duration Seconds to Years, Days, Hours, Minutes, Seconds
For a recent project I needed to express the difference between date objects as a string. Here’s an algorightm I’ve been using for a while. This time in JavaScript. JavaScript isn’t my best language, so if you have any suggestions for improvement, please let me know.
function fmt_duration(seconds, detail) {
// Return a string containing the number of years, days, hours,
// minutes, and seconds in the given numeric seconds argument.
// The optional detail argument can limit the about of detail.
// Note: 1 year is treated as 365.25 days to approximate "leap
// years" TAGS: secToYMDHMS, secToDHMS
//
// Some Examples:
//
// fmt_duration(35000000)
// returns "1 year, 39 days, 20 hours, 13 minutes, 20 seconds"
//
// fmt_duration(24825601)
// returns "287 days, 8 hours, 1 second"
//
// fmt_duration(24825601, 3)
// returns "287 days, 8 hours"
//
// fmt_duration(24825601, 1)
// returns "less than one year"
//
"use strict";
var labels = ['years', 'days', 'hours', 'minutes', 'seconds'],
increments = [31557600, 86400, 3600, 60, 1],
result = "",
i,
increment,
label,
quantity;
detail = detail === undefined ? increments.length : detail;
detail = Math.min(detail, increments.length);
for (i = 0; i < detail; i += 1) {
increment = increments[i];
label = labels[i];
if (seconds >= increment) {
quantity = Math.floor(seconds / increment);
if (quantity === 1) {
// if singular, strip the 's' off the end of the label
label = label.slice(0, -1);
}
seconds -= quantity * increment;
result = result + " " + quantity + " " + label + ",";
}
}
result = result.slice(1, -1);
if (result === "") {
result = "less than one " + labels[detail - 1].slice(0, -1);
}
return result;
}