/** 获取上个月日期 */ getLastMonthDays(year, month) { let nowMonthFirstDays = new Date(year, month - 1, 1).getDay() let lastMonthDays = [] if (nowMonthFirstDays) { //判定当月的第一天是不是星期天 //上个月体现多少天 let lastMonthNums = month - 1 < 0 ? this.getThisMonthDays(year - 1, 12) : this.getThisMonthDays(year, month - 1); //判定是否会跨年 //上个月从几号开始体现 for (let i = lastMonthNums - nowMonthFirstDays + 1; i <= lastMonthNums; i++) { let time = new Date(year, month - 2, i).toLocaleDateString() //对应的时间 lastMonthDays.push({ date: i, //几号 week: this.data.weeksArr[new Date(year, month - 2, i).getDay()], //星期几 time, isNowMonthDay: '' }); } } this.setData({ lastMonthDays }) console.log(lastMonthDays); },
打印效果可以看到 ,已经拿到上个月的日期已经对应的数据
⚠️:安卓手机上会存在bug,写法造成的,办理方法我放到文章末了
上个月的日期已经拿到了,下面可以在dom里渲染这个【lastMonthDays】数组了
下面在编写获取当月日期的方法
getNowMonthDays(year, month) { let { nowMonth, nowDay } = this.data let nowMonthDays = [] let days = this.getThisMonthDays(year, month); //获取当月的天数 for (let i = 1; i <= days; i++) { let d = new Date(year, month - 1, i) let years = d.getFullYear() let months = d.getMonth() + 1 let day = d.getDate() let time = `${years+'/'+months +'/'+day}` // 2023/3/3 nowMonthDays.push({ date: i, //几号 week: this.data.weeksArr[new Date(year, month - 1, i).getDay()], //星期几 time, color: false, //为已打卡日期样式做准备 day, //反面会改成夏历 isNowMonthDay: (month == nowMonth && i == nowDay) ? "isNowMonthDay" : "" }); } this.setData({ nowMonthDays }) console.log(nowMonthDays); },