简体   繁体   English

如何格式化momentjs持续时间是人类可读的?

[英]How to format a momentjs Duration to be human-readable?

I have an array of ISO 8601 durations that I want to sum, and then display in a human readable format. 我有一系列ISO 8601持续时间,我想要求和,然后以人类可读的格式显示。 The times look like PT10M33S , PT3H00M00S , PT50H23M15S . 时代看起来像PT10M33SPT3H00M00SPT50H23M15S 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. 我用moment jsmoment.duration()解析它们但是当我把它们加在一起时我不知道如何把它们变成可读的东西。

according to the moment docs https://momentjs.com/docs/#/durations/humanize/ you could do: 根据当时的文档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

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. 花了几个小时后,我发现了moment-duration-format插件。 You would call .format() on a duration object and pass a string that formats it to what you want to display. 您可以在持续时间对象上调用.format()并传递一个将其格式化为您要显示的字符串。 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'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM