I have an array of ISO 8601 durations that I want to sum, and then display in a human readable format. The times look like PT10M33S
, PT3H00M00S
, PT50H23M15S
. I used moment js to parse them with moment.duration()
but when I add them together I don't know how to turn them into something readable.
according to the moment docs https://momentjs.com/docs/#/durations/humanize/ you could do:
duration.humanize();
// or if the duration is given in other values like seconds:
moment.duration(60, "seconds").humanize(); // a minute
to display duration in a custom format:
moment.utc(duration.as('milliseconds')).format('HH:mm:ss');
After spending a few hours, I discovered the moment-duration-format
plugin. You would call .format()
on a duration object and pass a string that formats it to what you want to display. Here is what I ended up writing:
function formatDuration(duration, format_string) {
var length;
if (format_string === "long") {
format = [
duration.months() === 1 ? "Month" : "Months",
duration.days() === 1 ? "Day" : "Days",
duration.hours() === 1 ? "Hour" : "Hours",
duration.minutes() === 1 ? "Minute" : "Minutes",
duration.seconds() === 1 ? "Second" : "Seconds"
];
length = duration.format("M [" + format[0] + "] d [" + format[1] +
"] h [" + format[2] + "] m [" + format[3] + " and] s [" + format[4] + "]");
} else if (format_string === "short") {
length = duration.format("M[m] d[d] h:mm:ss");
} else {
length = duration.format(format_string);
};
return length;
};
What about this:
> var d = moment.duration(125, 's')
undefined
> moment().subtract(d).fromNow().replace(/ ago/, '')
'2 minutes'
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.