jsmreese / moment-duration-format

Format function plugin for the Moment Duration object.
MIT License
968 stars 120 forks source link

Calling .format() with escaped character produces unexpected results #110

Open ackmanx opened 6 years ago

ackmanx commented 6 years ago

I just upgraded from 1.3.0 to 2.2.2 and have failing unit tests.

expect(moment.duration(121, 'minutes').format('h [hr.]')).toEqual('2 hr.')

This now fails with a result of 2 hrs instead of 2 hr.

How can I get my expected output? I tried various combinations of the format string.

jsmreese commented 6 years ago

What's happening is that hr is auto-detected as the singular short form of the h token's units. So 2 hr. is updated to 2 hrs.

And . characters are automatically trimmed from the end of formatted strings. So 2 hrs. becomes 2 hrs.

You can set usePlural to false to stop the auto-pluralization of the units string.

moment.duration(121, 'minutes').format('h [hr]', { usePlural: false })
// "2 hr"

To get the . at the end, you'll need to add that back manually for now. There may be a way to detect that the user really means to have a . character at the end of the formatted string, and that it's not just an artifact left over from trimming. I'll give it some thought.

See https://github.com/jsmreese/moment-duration-format#useplural And https://github.com/jsmreese/moment-duration-format#punctuation-trimming