js获取某个月的星期每周的集合
先看返回的数据格式

//获取某个月的星期每周的集合,date所在的月份的
function getWeeksInMonth(date) {
let year = date.getFullYear()
let month = date.getMonth() + 1;
const firstDayOfMonth = new Date(year, month - 1, 1);
const lastDayOfMonth = new Date(year, month, 0);
const weeks = [];
const currentDay = new Date(firstDayOfMonth);
let weekNumber = 0;
const weekNumberCn = ["一", "二", "三", "四", "五", "六"]; // 最多六周
let isEnd = true;
while (isEnd) {
const startOfWeek = new Date(currentDay);
const endOfWeek = new Date(currentDay);
// 获取本周的开始日期(周一)
startOfWeek.setDate(currentDay.getDate() - currentDay.getDay() + (currentDay.getDay() === 0 ? -5 : 2));
// 获取本周的结束日期(周日)
endOfWeek.setDate(currentDay.getDate() - currentDay.getDay() + (currentDay.getDay() === 0 ? 1 : 8));
let list = []//本周的日期集合
const current = new Date(startOfWeek);
while (current <= endOfWeek) {
list.push(new Date(current).toISOString().slice(0, 10));
current.setDate(current.getDate() + 1);
}
weeks.push({
weekNumber: "第" + weekNumberCn[weekNumber] + "周",
start: startOfWeek.toISOString().slice(0, 10),
end: endOfWeek.toISOString().slice(0, 10),
list: list,
});
weekNumber++;
if (endOfWeek <= lastDayOfMonth) {
currentDay.setDate(currentDay.getDate() + 7);
} else {
isEnd = false;
}
}
return weeks;
}

浙公网安备 33010602011771号