这能满足您的需求吗?我使用了一些数组分块和日期函数将任何给定月份的日期分成各自的星期:
const getWeeks = (month, year) => Array(new Date(year, month, 0).getDate()).fill(0).map((_,i) => new Date(year, month-1, i+1)).map((d,i,a) => !i && d.getDay() ? [Array(d.getDay()).fill(null), d.getDate()] : d.getDate() === a.length && d.getDay() < 6 ? [d.getDate(), Array(6-d.getDay()).fill(null)] : d.getDate()).flat(2).map((d,i,a) => a.length ? a.splice(0,7) : null).filter(w => w);
// February 2021
getWeeks(2, 2021); // -> returns array below ↓↓↓
[
[null, 1, 2, 3, 4, 5, 6],
[ 7, 8, 9, 10, 11, 12, 13],
[ 14, 15, 16, 17, 18, 19, 20],
[ 21, 22, 23, 24, 25, 26, 27],
[ 28, null, null, null, null, null, null]
]
如果您不想使用 null 占位符,而只是在一周的天数较少时使用较短的数组,我们可以使用额外的过滤器来实现这一点。我们甚至可以为这个值包含一个可选参数,当它留空(或设置为未定义)时,将产生修剪后的数组:
const getWeeks = (month, year, nullVal) => Array(new Date(year, month, 0).getDate()).fill(0).map((_,i) => new Date(year, month-1, i+1)).map((d,i,a) => !i && d.getDay() ? [Array(d.getDay()).fill(nullVal), d.getDate()] : d.getDate() === a.length && d.getDay() < 6 ? [d.getDate(), Array(6-d.getDay()).fill(nullVal)] : d.getDate()).flat(2).map((d,i,a) => a.length ? a.splice(0,7) : null).filter(w => w).map(w => nullVal !== undefined ? w : w.filter(d => d));
// December 2021
getWeeks(12, 2021); // -> bullish value blank :: trimming weeks, returns array below ↓↓↓
[
[ 1, 2, 3, 4],
[ 5, 6, 7, 8, 9, 10, 11],
[12, 13, 14, 15, 16, 17, 18],
[19, 20, 21, 22, 23, 24, 25],
[26, 27, 28, 29, 30, 31 ]
]
getWeeks(12, 2021, 0); // -> using 0 as nullish value, returns array below ↓↓↓
[
[ 0, 0, 0, 1, 2, 3, 4],
[ 5, 6, 7, 8, 9, 10, 11],
[12, 13, 14, 15, 16, 17, 18],
[19, 20, 21, 22, 23, 24, 25],
[26, 27, 28, 29, 30, 31, 0]
]
您还可以使用此函数通过周的索引值获取一个月中的周数或特定周中的日期:
// Get number of weeks in month
getWeeks(12, 2021).length // -> 5
// Get dates in a week by index value
getWeeks(5, 2021)[2] // -> [9, 10, 11, 12, 13, 14, 15]