前两天做了一个项目预约时需要处理未来一周日期;就用原生js整了一个虽然有点繁琐,但能用
直接先看效果吧
接下来看怎么实现的
先获取当前日期并将其转换成xxx-xx-xx的格式
然后声明一个数组在其放入星期
然后根据当前日期获取当前周几(周日开始;周日为0;周一为1);
并根据次来截取日期
然后再创建两个数组将其放入数组中并匹配就可以了——完整代码奉上
let that = this; // 获取当前的日期 var now = new Date(); // 从日期对象中获取年份、月份和日期 var year = now.getFullYear(); var month = now.getMonth() + 1; var day = now.getDate(); that.day = day; // 将年份、月份和日期拼接成字符串yyyy-mm-dd格式 var dateStr = year + '年' + month + '月' + day + '日'; that.time = dateStr; const timestamp = Date.now(); const date = new Date(timestamp); const dayOfWeek = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'][date.getDay()]; // console.log(num,"num"); let week = that.monday; let weeks = that.monday; let daynum = date.getDay(); let obj = week.splice(0, daynum); // console.log(obj); let objs = weeks.splice(daynum, 6); let lobg = []; for (let i = 0; i < num.length; i++) { lobg.push(num[i]); } for (let i = 0; i < objs.length; i++) { lobg.push(objs[i]); } for (let i = 0; i < obj.length; i++) { lobg.push(obj[i]); } that.week = lobg; let today = new Date(); // 创建一个空数组来存储未来一周的日期 let futureDates = []; let timeDay = []; // 循环七次,每次增加一天并将其添加到日期数组中 for (let i = 0; i < 7; i++) { let futureDate = new Date(today.getTime() + (i * 24 * 60 * 60 * 1000)); // 格式化日期为字符串,并添加到数组中 futureDates.push(`${futureDate.getDate().toString().padStart(2, '0')}`); timeDay.push( `${futureDate.getFullYear()}-${(futureDate.getMonth() + 1).toString().padStart(2, '0')}-${futureDate.getDate().toString().padStart(2, '0')}` ) } this.day = futureDates; this.timeDay = timeDay;