给定来自 API 的秒数持续时间duration_seconds = 86485
.
(1天0小时1分1秒)
我打算使用 moment.js 将其转换为格式化的持续时间,如下所示:
1. {d} {hh}:{mm}:{ss} (1d 00:01:01)
2. {d}d {hh}h m{mm} s{ss} (1d 04h 30m 23s)
我还想确保以下几点:
- 如果天数为 0 (
00:01:01
- 1分1秒)
- hh:mm:ss 永远不会被修剪,1 秒显示为
00:00:01
.
我可以这样创建持续时间:
moment.duration(duration_seconds, 'seconds')
humanize 函数并不适合它的近似值。
我也可以自己写:
duration.get('d')
duration.get('h')
duration.get('m')
duration.get('s')
我似乎找不到内置函数,但我认为这是一个显而易见的函数?我是否缺少某些东西,否则我可以将其 PR 到时刻库中。
这似乎暗示该功能仍然不存在:使用 moment.js,如何将持续时间简化为其最简单的形式? https://stackoverflow.com/questions/42079230/using-moment-js-how-can-i-simplify-a-duration-to-its-most-simplified-form
The 时刻-持续时间-格式 https://github.com/jsmreese/moment-duration-format插件可以帮助你做到这一点。
// your input
var duration_seconds = 86485;
// create a moment-duration object
var duration = moment.duration(duration_seconds, 'seconds');
// format the object with a string
var formatted = duration.format('h[h] m[m] s[s]');
// displaying the output here
document.getElementById('output').innerHTML = formatted;
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment-duration-format/1.3.0/moment-duration-format.min.js"></script>
<div id="output" />
请注意,默认情况下它会省略不相关的单位,因此如果您的输入是 3,它只会说"3s"
, not "0h 0m 3s"
.
如果您想更改此行为,请设置trim:false
, 根据文档 https://github.com/jsmreese/moment-duration-format#trim。例如,要获取您在评论中提到的格式,请使用:
.format('hh:mm:ss', { trim: false })
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)