[英]Affected days of time range with moment.js
我嘗試遍歷兩個給定的日期時間。 我必須對范圍的每一天進行一些計算。 我做了一個JsBin來設置問題。
const timeRange1 = ['2019-10-22 14:00:00', '2019-10-22 19:00:00']; const timeRange2 = ['2019-10-22 13:30:00', '2019-10-24 10:00:00']; const timeRange3 = ['2019-10-22 06:00:00', '2019-10-23 23:00:00']; const timeRange4 = ['2019-10-21 23:00:00', '2019-10-22 01:00:00']; function loop(range) { const rangeStart = moment(range[0]) const rangeEnd = moment(range[1]) let i = 0 for (let m = rangeStart; m.diff(rangeEnd, 'days') <= 0; m.add(1, 'days')) { i++ } return i } // Here you can see the expected values and the wrong results. console.log(loop(timeRange1)); // 1 - 2 console.log(loop(timeRange2)); // 3 - 3 console.log(loop(timeRange3)); // 2 - 3 console.log(loop(timeRange4)); // 2 - 2
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>
這似乎來自時代。 當范圍結束的時間部分高於范圍開始的時間部分時,添加一天不會使差異低於 0。
如果你從你的時刻值中截斷它們,結果就是你所期望的(使用.startOf('day')
)
function loop(range) {
const rangeStart = moment(range[0]).startOf('day')
const rangeEnd = moment(range[1]).startOf('day')
let i = 0
for (let m = rangeStart; m.diff(rangeEnd, 'days') <= 0; m.add(1, 'days')) {
i++
}
return i
}
問題是diff被截斷為 integer,因此循環在差異至少1 天之前不會停止。 考慮第一個例子:
第一次迭代:
第二次迭代:
第三次迭代
比較需要:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.