jsmreese / moment-duration-format

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

Only display when values are not zero in hh:mm:ss format #127

Closed shaifulborhan closed 6 years ago

shaifulborhan commented 6 years ago

Hi,

If I have the following code, is it possible to not show minutes or hours if their values are zero?

var formatted = moment.duration(seconds, 'seconds').format("HH[h] mm[m] ss[s]", { trim: false });

For example: If I have 18 seconds, the output would be 18s instead of 00h 00m 18s. If I have 200 seconds, the output would be 03m 20s instead of 00h 03m 20s.

Thank you.

shaifulborhan commented 6 years ago

Got it. Should set the trim to "all".

jsmreese commented 6 years ago

You have a couple options based on the specifics of how you want to trim zero-value tokens. Consider what happens in the case of seconds === 0 (zero hours, zero minutes, zero seconds) and seconds === 360 (zero hours, zero seconds).

moment.duration(360, 'seconds').format("HH[h] mm[m] ss[s]", { trim: false });
// "00h 06m 00s"

// trim: "left" is the default, and equivalent to not setting the trim option
moment.duration(360, 'seconds').format("HH[h] mm[m] ss[s]", { trim: "left" });
// "06m 00s"
moment.duration(360, 'seconds').format("HH[h] mm[m] ss[s]");
// "06m 00s"

moment.duration(360, 'seconds').format("HH[h] mm[m] ss[s]", { trim: "all" });
// "06m"

moment.duration(0, 'seconds').format("HH[h] mm[m] ss[s]", { trim: "all" });
// ""
moment.duration(0, 'seconds').format("HH[h] mm[m] ss[s]", { trim: "left" });
// "00s"

// The token length of your first token affects trimming. See the forceLength option.
moment.duration(0, 'seconds').format("H[h] mm[m] ss[s]", { trim: "left" });
// "0s"