一、函数代码
// 1.处理日期格式
getDate(datestr) {
let temp = datestr.split('-')
let date = new Date(temp[0], temp[1] - 1, temp[2])
return date
},
// 2.获取时间段内的所有日期 Spacer:间隔符
formatEveryDay(start, end, Spacer) {
let weekArr = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六']
let dateList = []
let startTime = this.getDate(start)
let endTime = this.getDate(end)
while ((endTime.getTime() - startTime.getTime()) >= 0) {
let year = startTime.getFullYear()
let month = startTime.getMonth() + 1 < 10 ? '0' + (startTime.getMonth() + 1) : startTime.getMonth() + 1
let day = startTime.getDate().toString().length == 1 ? '0' + startTime.getDate() : startTime.getDate()
let timeDay = startTime.getDay(startTime)
// dateList.push({
// time: year + '-' + month + '-' + day,
// week: weekArr[startTime.getDay(startTime)],
// isWeekend: timeDay === 0 || timeDay === 6
// })
if (Spacer) {
// 如果不需要间隔符则直接拼接返回
if (Spacer === 'null') {
dateList.push(year + month + day) // 如20220422,20220423
} else {
// 需要自定义间隔符
dateList.push(year + Spacer + month + Spacer + day)
}
} else {
dateList.push(year + '-' + month + '-' + day) // 2022-04-22,2022-04-23
}
startTime.setDate(startTime.getDate() + 1)
}
return dateList
}
二、示例
1. 执行:formatEveryDay(‘2022-06-14’,‘2022-07-01’)
2. 自定义分隔符 Spacer
formatEveryDay(‘2022-06-14’,‘2022-07-01’,‘-’)
三、获取指定时间范围内的全部日期,并对应星期几,是否周末
function formatEveryDay(start, end) {
let weekArr = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六']
let dateList = []
let startTime = this.getDate(start)
let endTime = this.getDate(end)
while ((endTime.getTime() - startTime.getTime()) >= 0) {
let year = startTime.getFullYear()
let month = startTime.getMonth() + 1 < 10 ? '0' + (startTime.getMonth() + 1) : startTime.getMonth() + 1
let day = startTime.getDate().toString().length == 1 ? '0' + startTime.getDate() : startTime.getDate()
let timeDay = startTime.getDay(startTime)
dateList.push({
time: year + '-' + month + '-' + day,
week: weekArr[startTime.getDay(startTime)],
isWeekend: timeDay === 0 || timeDay === 6
})
startTime.setDate(startTime.getDate() + 1)
}
return dateList
}
执行:formatEveryDay(‘2022-06-14’,‘2022-07-01’)