0

I have a transformation to make. I am using MomentJS, and I am trying to take milliseconds and convert them to the format 1 Hour and 7 Mins for example.

I can make it work like this 1,1 Hours with the following code, where interval is the time in ms:

moment
      .duration(interval)
      .asSeconds()
      .toFixed(0)

How can I make this work. Take ms and transform them into human-readable formats.

By the way, I tried the humanize method, but didn't cover them. Just FYI..

1 Answers1

0

Moment doesn't seem to support what you are asking out of the box, but you can get the values of various time units (years, months, days ...) of your duration using the get function.

Based on this information, I put together a couple of functions that generate the output you are looking for:

let duration = moment.duration(122101000);

let units = [
  {unit: "years", singular: "Year", plural: "Years"},
  {unit: "months", singular: "Month", plural: "Months"},
  {unit: "days", singular: "Day", plural: "Days"},
  {unit: "hours", singular: "Hour", plural: "Hours"},
  {unit: "minutes", singular: "Minute", plural: "Minutes"},
  {unit: "seconds", singular: "Second", plural: "Seconds"}
];

console.log(output(deconstruct(duration, units)));

function output(entries)
{
  let result = "";
  for (let i = 0; i < entries.length; i++) {
    let entry = entries[i];
    if (i > 0) {
      result += ', ' + (i == entries.length - 1 ? "and " : "");
    }
    result += entry.unitValue + " " + (entry.unitValue == 1 ? entry.unit.singular : entry.unit.plural);
  }
  return result;
}

function deconstruct(duration, units)
{
  let values = [], unitValue;
  for (let unit of units) {
    if (unitValue = duration.get(unit.unit)) {
      values.push({"unitValue": unitValue, "unit": unit})
    }
  }
  return values;
}
<script src="https://cdn.jsdelivr.net/momentjs/2.14.1/moment-with-locales.min.js"></script>
radu
  • 114
  • 2
  • 7