在将来使用unix timstamp的情况下,如何使用Moment.js获取到那时为止的小时数,分钟数和秒数?
例如:
now = 1589252712837
time = 1589356202907
// This is the line I do not know
res = moment(time - now)
console.log(res)
// 23 hours, 12 minutes, 3 seconds
编辑:
我相信我可以做这样的事情,但是有原生的方法吗?
now = 1589252712837
time = 1589356202907
remaining = time - now
hour = moment(remaining).hour()
minute = moment(remaining).minute()
second = moment(remaining).second()
console.log(`${hour} hours, `${minute} minutes, ${seconds} seconds`)
// 23 hours, 12 minutes, 3 seconds
请注意,示例代码具有时间偏移量:remaining/1000/60/60
〜= 28,而不是23。您需要使用moment.utc
。但我不建议您这样做,因为您会遇到其他问题,例如处理几天和几个月。
至于“本地”支持,请在此处进行详细讨论:https : //github.com/moment/moment/issues/463
TL; DR:从2012年至今讨论。并且,在文档中,它们指向“矩持续时间格式”插件。如果您想要接近“本地”支持的内容,请查看此插件:https :
//github.com/jsmreese/moment-duration-format
老实看了一下情况,如果是我,我可能只会使用moment-duration-format,或者只是使用humanize()
。也许我自己讲类似duration._data的生成方式+ Intl.NumberFormat,这是我猜到的矩持续时间格式基本上已经在做的事情。
据我所知,我将列出一些可能的方法:
now = 1589252712837
time = 1589356202907
remaining = time - now
// extract key(units),value from parsed ._data property of duration
// no additional dependencies but depends on internal private variable _data
console.log(
Object.entries(moment.duration(remaining,'milliseconds')._data).reverse()
.flatMap(([unit,value])=>value!==0?`${value} ${unit}`:[]).join(' ')
);
// using moment-duration-format plugin
console.log(moment.duration(remaining,'milliseconds').format('h [hours] m [minutes] s [seconds]'))
// twitter style humanize
console.log(moment.duration(remaining,'milliseconds').humanize());
// hours threshhold is Infinity; never round up to higher units than hours
console.log(moment.duration(remaining,'milliseconds').humanize({h:Infinity}));
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.25.3/moment.min.js"></script>
<!-- moment-duration-format plugin -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment-duration-format/2.3.1/moment-duration-format.min.js"></script>
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句