//全部时间的月份都是按0~11基准,显示月份才+1
let dateArr = []; //需要遍历的日历数组数据
let arrLen = 0; //dateArr的数组长度
let now = setYear ? new Date(setYear, setMonth) : new Date();
let year = setYear || now.getFullYear();
let nextYear = 0;
let month = setMonth || now.getMonth(); //没有+1方便后面计算当月总天数
let nextMonth = (month + 1) > 11 ? 1 : (month + 1);
let ss = year + ‘,’ + (month + 1) + ‘,’ + 1;
console.log(ss);
if(this.data.isIOS){
ss = ss.replace(/-/g, ‘/’);
}
console.log(ss);
let startWeek = new Date(ss).getDay(); //目标月1号对应的星期
let dayNums = new Date(year, nextMonth, 0).getDate(); //获取目标月有多少天
let obj = {};
let num = 0;
let laseMothYear = year;//上个月份所属年份
let laseMoth = (month - 1) < 0 ? 11 : month - 1;//上个月份,由当月-1得出,若小于0则为上一年11月
let laseMothdayNums = new Date(laseMothYear, laseMoth, 0).getDate();
if (month - 1 < 0) {//上个月份,由当月-1得出,若小于0则为上一年11月
laseMothYear=year-1;
laseMothdayNums = new Date(laseMothYear, laseMoth, 0).getDate();//上个月份天数
}
if (month + 1 > 11) {
nextYear = year + 1;
dayNums = new Date(nextYear, nextMonth, 0).getDate();
}
arrLen = startWeek + dayNums;
let iMonthleng = startWeek + dayNums;//除去下个月份的集合长度
let yu = arrLen % 7;
if (yu!=0){
arrLen = startWeek + dayNums + 7 - yu;
}
for (let i = 0; i < iMonthleng; i++) {
if (i >= startWeek) {//当月天数
num = i - startWeek + 1;
obj = {
isToday: ‘’ + year + (month + 1) + num,
dateNum: num,
}
} else {// 上个月的天数
obj = {
isToday: ‘’ + laseMothYear + (laseMoth + 1) + laseMothdayNums - startWeek + i + 1,
isToMonth:0,
dateNum: laseMothdayNums-startWeek+i+1,//上个月天数数字
};
}
dateArr[i] = obj;
}
if(yu!=0){//下个月天数 因为总是从1开始所以直接循环增加
let daynumber=1;
for (let i = iMonthleng; i < arrLen;i++) {
obj = {
isToday: ‘’ + laseMothYear + (laseMoth + 1) + laseMothdayNums - startWeek + i + 1,
isToMonth: 0,//该天数是否属于当月
dateNum: daynumber,
};
dateArr[i] = obj;
daynumber++;
}
}
this.setData({
dateArr: dateArr
})
let nowDate = new Date();
let nowYear = nowDate.getFullYear();
let nowMonth = nowDate.getMonth() + 1;
let nowWeek = nowDate.getDay();
let getYear = setYear || nowYear;
let getMonth = setMonth >= 0 ? (setMonth + 1) : nowMonth;
if (nowYear == getYear && nowMonth == getMonth) {
this.setData({
isTodayWeek: true,
todayIndex: nowWeek
})
} else {
this.setData({
isTodayWeek: false,
todayIndex: -1
})
}
以上代码…