一. 遇事原因
最近项目里的排班管理,显示要获取本周开始的第一天到最后一天 表格里点击排班 如下图所示
二.写法
框架用的是 vue 这些是写在 methods 里的封装的函数,上方 data 里记得定义一个 weekDates,
封装时间函数
bz(time) {
let date
if (time) {
date = new Date(time);
} else {
date = new Date(); // 可以传入任意一个日期
}
this.weekDates = this.getWeekDates(date); // 获取本周一到本周日的日期
this.weekDates.forEach((item, index) => {
this.weekDates[index] = this.format(item)
})
},
format(time) {
let nowTime = new Date(time)
let year = nowTime.getFullYear()
let month = (nowTime.getMonth() + 1) < 10 ? "0" + (nowTime.getMonth() + 1) : (nowTime.getMonth() + 1)
let day = nowTime.getDate() < 10 ? "0" + nowTime.getDate() : nowTime.getDate()
return year + "-" + month + "-" + day
},
getWeekDates(date) {
const weekDates = [];
const dayOfWeek = date.getDay(); // 获取给定日期的星期几,0表示星期日,1表示星期一,以此类推
// 计算本周一的日期
const monday = new Date(date);
monday.setDate(date.getDate() - dayOfWeek + (dayOfWeek === 0 ? -6 : 1));
weekDates.push(monday);
// 计算本周二到本周六的日期
for (let i = 1; i <= 5; i++) {
const day = new Date(date);
day.setDate(date.getDate() - dayOfWeek + i + (dayOfWeek === 0 ? 0 : 1));
weekDates.push(day);
}
// 计算本周日的日期
const sunday = new Date(date);
sunday.setDate(date.getDate() - dayOfWeek + 7);
weekDates.push(sunday);
return weekDates;
},
调用方法
这段我是写在 watch 监听里的,当我点击左上方的上周 本周 下周 下下周时触发的函数,分别获取的是上周的周一到周日的年月日 ➡ 本周的周一到周日的年月日 ➡ 下周的周一到周日的年月日 ➡ 下下周的周一到周日的年月日
whichWeek(val) {
if (val == -1) {
this.bz(new Date().getTime() - 60 * 1000 * 60 * 24 * 7)
} else if (val == 0) {
this.bz()
} else if (val == 1) {
this.bz(new Date().getTime() + 60 * 1000 * 60 * 24 * 7)
} else if (val == 2) {
this.bz(new Date().getTime() + 60 * 1000 * 60 * 24 * 14)
}
},