Search code examples
javascriptmomentjsiso8601

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. 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.


Solution

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