如何将 momentjs Duration 格式化为人类可读的?

How to format a momentjs Duration to be human-readable?

我有一个 ISO 8601 持续时间数组,我想对其求和,然后以人类可读的格式显示。 时间看起来像 PT10M33SPT3H00M00SPT50H23M15S。我用 moment jsmoment.duration() 解析它们,但是当我把它们加在一起时,我不知道如何把它们变成可读的东西。

花了几个小时后,我发现了 moment-duration-format 插件。您可以在持续时间对象上调用 .format() 并传递一个字符串,将其格式化为您想要显示的内容。这是我最后写的:

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;
};

这个怎么样:

> var d = moment.duration(125, 's')
undefined
> moment().subtract(d).fromNow().replace(/ ago/, '')
'2 minutes'

根据目前的文档 https://momentjs.com/docs/#/durations/humanize/ 你可以这样做:

duration.humanize();
// or if the duration is given in other values like seconds:
moment.duration(60, "seconds").humanize(); // a minute

以自定义格式显示持续时间:

moment.utc(duration.as('milliseconds')).format('HH:mm:ss');