我正在使用date-fns库构建日历,我需要获得一个月的星期数。
let start = startOfMonth(date)
let end = endOfMonth(date)
let firstWeek = getISOWeek(start)
let lastWeek = getISOWeek(end)
let weeks = []
for (let i = firstWeek; i < lastWeek + 1; i++) {
weeks.push(i)
}
return weeks
这对大多数月份都适用,除了12月这一周为空,因为firstWeek和lastWeek分别为“ 48”和“ 1”,这对大多数月份都有效。
我知道我可以使用更复杂的循环来解决此问题,以检查每次迭代是否高于或低于先前的迭代,但是我想知道是否存在使用date-fns实现此目的的更自然/简单的方法(或es6)。
答案 0 :(得分:0)
Would be better to defer getting of the ISO week and iterate over the actual dates, instead of dealing with week index numbers.
let startOfCurrent = startOfMonth(date)
let startOfNext = addMonths(startOfCurrent, 1)
let weeks = []
for (let i = startOfCurrent; isBefore(i, startOfNext); i = addWeeks(i, 1)) {
weeks.push(getISOWeek(i))
}
return weeks