Add milliseconds to formatDuration in date-fns

Viewed 2708

I want to convert a number of milliseconds to a human readable format using date-fns and React Native.

I've managed to do the conversion: interval > duration > human readable format and is works fine all the way to seconds but milliseconds are omitted.

Current code:

 const niceFormatDuration = (intervalInMs) => {
    const milliseconds = Number.parseInt(intervalInMs % 1000, 10);
    const duration = intervalToDuration({ start: 0, end: intervalInMs });
    return formatDuration(duration);
 };

The above code is working fine, but missing milliseconds. I've added the milliseconds to the duration object with:

duration["milliseconds"] = milliseconds;

But formatDuration still only returns down to seconds.

Also tried to add a new milliseconds format to formatDuration, but a error is thrown.

{
      format: [
        "years",
        "months",
        "weeks",
        "days",
        "hours",
        "minutes",
        "seconds",
        "milliseconds", // Not working with this line
      ],
    }

Obviously I could manually add the milliseconds in the end of the string, but that looks ugly:

return `${formatDuration(duration)} ${milliseconds} ms`;
1 Answers

From date-fns docs: https://date-fns.org/v2.19.0/docs/Duration

Duration object doesn't store milliseconds, so it's not possible.

Adding additional property to the object won't change the implementation of functions working with duration. Function simply doesn't expect nor looks for this property.

You need to append milliseconds by yourself.

Related