javascriptangularmomentjsangular-moment

Using Moment library, what is the correct syntax to convert minutes into days hours and minutes that also formats for singular vs plural?


Any help is greatly appreciated. I've been struggling to find a solution for this question:

  1. Using Moment library, what is the correct syntax to convert minutes into days hours and minutes that also formats for singular vs plural?

expected: 2009 minutes would become: 1 day 9 hours 29 minutes

here is the incorrect code:

function durationFormatter(minutes): string {
  const ms = minutes * 60000;
  const days = Math.floor(ms / 8.64e7);
  const msOnLastDay = ms - days * 8.64e7;

  return moment.utc(msOnLastDay)
    .format("D [days] H [hours] M [minutes]");
}

console.log('durationFormatter -->', durationFormatter(2009));

The above outputs:

1 days 9 hours 1 minutes which is wrong

I also tried this other moment package moment-duration-format with this syntax: (per docs = https://github.com/jsmreese/moment-duration-format#basics)

import momentDurationFormatSetup from 'moment-duration-format';

function durationFormatter(minutes): string {
  momentDurationFormatSetup();
  return moment.duration(minutes, "minutes").format();
}

But I get this error: Property 'format' does not exist on type 'Duration'

How would I use this with the package?


Solution

  • You can use the excellent library humanizeDuration, simply passing:

    humanizeDuration(2009 * 60 * 1000, { delimiter: ' '})

    will output what you wanted - 1 day 9 hours 29 minute.

    Note - you pass milliseconds, so you need to multiple the minutes parameter by 60,000 before passing to humanizeDuration