创建一个获取日期组的方法,根据传入的不同日期类型,返回不同的日期数组
type的枚举值:"YEAR"、"MONTH"、"DAY"
getDateList(type){
let dateList=[]
let year=new Date().getFullYear()
let month=new Date().getMonth()+1 //当前月份
let day=new Date().getDate()
console.log(year,month,day)
if(type==="YEAR"){
for (let i = 0; i < 5; i++) {
dateList.push(year-i)
}
}else if(type==="MONTH"){
for (let i = 0; i < 6; i++) {
if (month <= 0) {year = year - 1;month = month + 12;}
if (month < 10) {month = "0" + month;}
dateList[i] = year + "-" + month
month = month - 1
}
}else{
for (let i = 0; i < 7; i++) {
if (day-7<= 0) {
//1周前所在月的总天数
let endTimeMonthDay = new Date(year, parseInt(month) - 1, 0).getDate()
if (month - 1 <= 0) {
//如果在当年的1月份
if(day-i>0){
dateList.push(year + "-" + month + "-" + `0${day - i}`)
}else{
dateList.push(year-1 + "-" + 12 + "-" + (endTimeMonthDay - (i-day)))
}
} else {
if(day-i>0){
dateList.push(year + "-" + month + "-" + `0${day - i}`)
}else{
dateList.push(year + "-" + (month - 1) + "-" + (endTimeMonthDay - (i-day)))
}
}
}else{
if(day-i<10){
dateList.push(year + "-" + month + "-" + `0${day - i}`)
}else{
dateList.push(year + "-" + month + "-" + (day - i))
}
}
}
}
dateList=dateList.reverse()
return dateList
}
示例:
当前日期:
若month=3,获取近6个月如下(跨年取月份):
若month=3,day=4,获取近7天日期如下(跨月取日期):
若month=1,day=4,获取近7天日期如下(跨月跨年取日期):