考慮這個向下舍入到最近間隔的函式:
function roundToNearest(value, interval) {
return Math.floor(value/interval) * interval;
}
Date.now()
> 2022 年 9 月 1 日星期四 05:38:11 GMT 0300(東歐夏令時間)
現在運行 5 分鐘:
new Date(roundToNearest(Date.now(), 1000*60*5))
> 2022 年 9 月 1 日星期四 05:35:00 GMT 0300(東歐夏令時間)
15分鐘:
new Date(roundToNearest(Date.now(), 1000*60*15))
> 2022 年 9 月 1 日星期四 05:30:00 GMT 0300(東歐夏令時間)
1小時:
new Date(roundToNearest(Date.now(), 1000*60*60*1))
> 2022 年 9 月 1 日星期四 05:00:00 GMT 0300(東歐夏令時間)
2小時:
new Date(roundToNearest(Date.now(), 1000*60*60*2))
>Thu Sep 01 2022 03:00:00 GMT 0300(東歐夏令時間)(應為 04:00:00)
1 小時及以下的間隔回傳預期結果,但 2 小時(以及 2 小時以上的任何間隔)不會回傳(例如,04:00:00 預計為 2 小時)。如何修改它以使其在 1 小時以上的時間間隔內作業?
uj5u.com熱心網友回復:
我認為您在這里需要的是從午夜開始計算時間。也就是說,如果時間是 05:30,2 小時四舍五入你想要 04:00,或者 6 小時四舍五入你想要 00:00。
我們得到自當地午夜以來的間隔,四舍五入到所需的數字,然后添加到午夜。我們將創建一些輔助函式getMidnight()和getTimeSinceMidnight().
然后我們將組合起來創建一個roundSinceMidnight()函式。
function roundSinceMidnight(date, interval) {
return roundToNearest(getTimeSinceMidnight(date), interval) getMidnight(date);
}
function roundToNearest(value, interval) {
return Math.floor(value/interval) * interval;
}
function getMidnight(date) {
const d = new Date(date); // date could be a Date object or ms since 1970...
return new Date(d.getFullYear(), d.getMonth(), d.getDate()).getTime();
}
function getTimeSinceMidnight(date) {
return date - getMidnight(date);
}
console.log('1 hour: ', new Date(roundSinceMidnight(Date.now(), 1000*60*60*1)).toTimeString())
console.log('2 hours:', new Date(roundSinceMidnight(Date.now(), 1000*60*60*2)).toTimeString())
console.log('4 hours:', new Date(roundSinceMidnight(Date.now(), 1000*60*60*4)).toTimeString())
console.log('6 hours:', new Date(roundSinceMidnight(Date.now(), 1000*60*60*6)).toTimeString())
.as-console-wrapper { max-height: 100% !important; }
uj5u.com熱心網友回復:
您可能會忽略您所在時區的時差。讓我們減去 0300。03:00:00我不能證明它是正確的,但以下內容可能對您有用:
new Date(roundToNearest(Date.now() 1000*60*60*3, 1000*60*60*2) - 1000*60*60*3)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/504167.html
標籤:javascript 日期 数学
