function formatTime(date) {
const dt = new Date(date);
const y = dt.getFullYear();
const m = (dt.getMonth() + 1 + "").padStart(2, "0");
const d = (dt.getDate() + "").padStart(2, "0");
return `${y}-${m}-${d}`;
}
function getMonthWeeks(year, month) {
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 ? -6 : 1)
);
// 获取本周的结束日期(周日)
endOfWeek.setDate(
currentDay.getDate() -
currentDay.getDay() +
(currentDay.getDay() === 0 ? 0 : 7)
);
weeks.push({
weekNumber: "第" + weekNumberCn[weekNumber] + "周",
start: formatTime(startOfWeek),
end: formatTime(endOfWeek),
});
weekNumber++;
if (endOfWeek < lastDayOfMonth) {
currentDay.setDate(currentDay.getDate() + 7);
} else {
isEnd = false;
}
}
return weeks;
}
// 示例:获取2023年10月的周日期数组
const year = 2023;
const month = 10;
const monthWeeks = getMonthWeeks(year, month);
console.log(monthWeeks);
// [ { weekNumber: '第一周', start: '2023-09-25', end: '2023-10-01' },
// { weekNumber: '第二周', start: '2023-10-02', end: '2023-10-08' },
// { weekNumber: '第三周', start: '2023-10-09', end: '2023-10-15' },
// { weekNumber: '第四周', start: '2023-10-16', end: '2023-10-22' },
// { weekNumber: '第五周', start: '2023-10-23', end: '2023-10-29' },
// { weekNumber: '第六周', start: '2023-10-30', end: '2023-11-05' } ]
js实现根据年和月,生成所在月的周日期数组
最新推荐文章于 2024-04-07 11:41:15 发布