function countDaysOfWeekInRange(startDateStr, endDateStr, daysOfWeek) {
// 将字符串转换为Date对象
const startDate = new Date(startDateStr);
const endDate = new Date(endDateStr);
// 初始化计数器
let count = 0;
// 遍历日期范围
let currentDate = new Date(startDate);
while (currentDate <= endDate) {
// 获取当前日期的星期几(0为周日,1为周一,...,6为周六)
const dayOfWeek = currentDate.getDay();
// 检查当前日期是否是目标星期几之一
if (daysOfWeek.includes(dayOfWeek)) {
count++;
}
// // 将星期几的数字转换为字符串(例如,1 -> "周一")
// const dayOfWeekStr = ["周日", "周一", "周二", "周三", "周四", "周五", "周六"][dayOfWeek];
// if (daysOfWeek.includes(dayOfWeekStr)) {
// count++;
// }
// 移动到下一天
currentDate.setDate(currentDate.getDate() + 1);
}
return count;
}
// 调用函数并打印结果
const startDate = "2024-09-04 14:12:21";
const endDate = "2024-09-11 14:12:21";
const targetDays = [2, 3, 5, 6];
// const targetDays = ["周二", "周三", "周五", "周日"];
console.log(countDaysOfWeekInRange(startDate, endDate, targetDays)); // 输出结果 5
JS--时间段中有几个符合条件的天数(周几)
于 2024-09-04 14:30:03 首次发布