簡體   English   中英

如何使用 moment.js 從 unix 時間戳中獲取剩余的小時、分鍾和秒?

[英]How to use moment.js to get remaining hours, minutes, and seconds from a unix timestamp?

給定未來的 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 年到現在一直在討論。 而且,在文檔中,他們指向了moment-duration-format插件。 如果您想要接近“本機”支持的東西,請查看此插件:
https://github.com/jsmreese/moment-duration-format

老實說,在查看了情況之后,如果是我,我可能只會使用moment-duration-format ,或者只是使用humanize() 也許我自己的類似於duration._data的生成方式+ Intl.NumberFormat,這就是我猜moment-duration-format基本上已經在做的事情。

據我所知,我將列出一些可能的方法:

 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>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM