js返回未来或过去7天等时间合集(任意日期区间合集)
/**
* 时间前后向前推算时间集合
* @param {string:before|after} timebd:获取时间往后推,还是往前推,
* @param {boole} haveCurrentDay:包不包含当天时间,
* @param {number} Days:计算几天的时间,
* @param {string:"2023-11-02"} timing:指定不指定当天的日期
* @return {array}数据集合
*/
function nextDay(timebd,haveCurrentDay,Days,timing){//
let today = new Date() //获取今天的日期
if (timing) {
today = new Date(timing)
}
let date2 = new Date(today);
let dateArray = []
timebd=timebd ? timebd:"after"
haveCurrentDay=haveCurrentDay ? true:false
Days=Days ? Days:7
function TimestampToDate2(Timestamp) {
let now = new Date(Timestamp),
y = now.getFullYear(),
m = now.getMonth() + 1,
d = now.getDate();
return y + "-" + (m < 10 ? "0" + m : m) + "-" + (d < 10 ? "0" + d : d);
}
let fori=haveCurrentDay ? 0:1;
let fortotal=haveCurrentDay ? Days:Days+1;
for(let i = fori; i < fortotal; i++){
let everyDay=""
if (timebd=="after") {//未来
everyDay=date2.setDate(today.getDate() + i)
}else{//过去
everyDay=date2.setDate(today.getDate() - i)
}
dateArray.push(TimestampToDate2(everyDay)) //获取未来7天内的日期
}
if (timebd=="after") {//未来
return dateArray
}else{//过去
return dateArray.reverse()
}
}
返回结果
console.log(nextDay())
//(7) ['2023-11-09', '2023-11-10', '2023-11-11', '2023-11-12', '2023-11-13', '2023-11-14', '2023-11-15']