拿到今天往后 最近的 多个 周几
方法及例子如下:
比如拿到今天往后 最近的 5个 周二(不包括今天)
参数:
weekday 是周几,参数范围是 0 - 6,0 代表周日
num 是个数
startDay 是开始计算的时间,是时间戳
function getDays(weekday, num, startDay, lastResult) {
// 判断
if ([0, 1, 2, 3, 4, 5, 6].indexOf(weekday) === -1) {
return 'weekday 错误'
}
if (num <= 0) {
return 'num 错误'
}
let todayDate = new Date()
let today =
todayDate.getFullYear() +
'-' +
(todayDate.getMonth() + 1) +
'-' +
todayDate.getDate()
if (startDay) {
if (typeof startDay !== 'number') {
return 'startDay 错误'
}
if (startDay < new Date(today).getTime()) {
return 'startDay 错误'
}
}
if (
lastResult &&
Object.prototype.toString.call(lastResult) !== '[object Array]'
) {
return 'lastResult 错误'
}
// 正文
let date = startDay ? new Date(startDay) : new Date()
let day = date.getDay()
let oneDay = 24 * 60 * 60 * 1000
let afterDay
let stepDays
let result = lastResult ? lastResult : []
if (day == weekday) {
stepDays = 7 * oneDay
} else if (day < weekday) {
stepDays = (weekday - day) * oneDay
} else if (day > weekday) {
stepDays = (7 - day + weekday) * oneDay
}
afterDay = new Date(date.getTime() + stepDays)
result.push(afterDay)
if (--num) {
getDays(weekday, num, afterDay.getTime(), result)
}
return result
}
let result = getDays(2, 5)
console.log(result)
/*
0: Tue Apr 12 2022 15:27:42 GMT+0800 (中国标准时间) {}
1: Tue Apr 19 2022 15:27:42 GMT+0800 (中国标准时间) {}
2: Tue Apr 26 2022 15:27:42 GMT+0800 (中国标准时间) {}
3: Tue May 03 2022 15:27:42 GMT+0800 (中国标准时间) {}
4: Tue May 10 2022 15:27:42 GMT+0800 (中国标准时间) {}
*/