当持续时间小于一小时时,使用moment.js以格式00:XX显示持续时间

Dan*_*ish 3 javascript momentjs

我正在尝试使用时刻持续时间格式来设置倒计时器的格式,但是一旦时间低于60分钟,则小时消失,例如60分钟显示为"01:00",这是正确的59分钟显示为"59",这是不正确的,它应显示为"00:59"

其中3500000毫秒等于58分钟

我有以下代码:

moment.duration(3500000).format("hh:mm", { forceLength: true })
Run Code Online (Sandbox Code Playgroud)

显示结果:58,而不是00:58

我在这做错了什么?

我也尝试过这种变化无济于事

moment.duration(3500000).format("HH:mm", { forceLength: true })
Run Code Online (Sandbox Code Playgroud)

小智 7

我可以解释发生了什么(我创建了moment-duration-format插件).

forceLength选项仅影响具有值的第一个标记,这意味着第一个标记的值大于0.在您的情况下,hh令牌没有值. https://github.com/jsmreese/moment-duration-format#force-length

切换hhHH表示用于格式化时刻对象(日期)的内容,但不是用于使用我的插件格式化时刻持续时间对象(时间长度)(除非您已经自定义了持续时间格式化标记,这可以使用我的插件).

使用moment(moment.duration(3500000)._data).format("HH:mm");建议是一个很好的创意解决方法.

如果你想获取存储库dev分支上的moment-duration-format版本,有一个选项可以提供帮助(参见https://github.com/jsmreese/moment-duration-format/issues/22). .

在该版本中,您可以使用该*字符表示修剪时显示的最小标记,即使它没有值:

moment.duration(3510000).format("*hh:mm");
--> "00:59"
moment.duration(3509999).format("*hh:mm");
--> "00:58"
Run Code Online (Sandbox Code Playgroud)

需要注意的是,在默认行为dev更改从分支版本truncateround,所以你从下降00:5900:58当你从传递58 minutes 30 seconds58 minutes 29 seconds.在该版本中,您可以打开trunc此输出的选项:

moment.duration(3539999).format("*hh:mm", { trunc: true });
--> "00:58"
moment.duration(3540000).format("*hh:mm", { trunc: true });
--> "00:59"
Run Code Online (Sandbox Code Playgroud)

不确定这是否是你想要的倒计时解决方案...也许设置floor(trunc)的功能ceiling,或round其余部分最好?

如果您想要一个天花板行为,您可以使用dev分支版本trunc并添加60000到您的计时器值:

moment.duration(3540000 + 60000).format("*hh:mm", { trunc: true });
--> "01:00"
moment.duration(3539999 + 60000).format("*hh:mm", { trunc: true });
--> "00:59"
moment.duration(3500000 + 60000).format("*hh:mm", { trunc: true });
--> "00:59"
moment.duration(3480000 + 60000).format("*hh:mm", { trunc: true });
--> "00:59"
moment.duration(3479999 + 60000).format("*hh:mm", { trunc: true });
--> "00:58"
Run Code Online (Sandbox Code Playgroud)


Jyo*_*aja 6

试试这个

moment(moment.duration(3500000)._data).format("HH:mm");
Run Code Online (Sandbox Code Playgroud)

  • 使用像`_data`这样的内部结构可能不是一个好主意 (6认同)
  • `moment.utc(3500000).format("HH:mm");` 在不依赖任何内部结构的情况下给出相同的结果。无论哪种方式,唯一的问题是它最多只能工作 24 小时。 (2认同)