1.有个需求要获得本周和本月日期代码如下, this.$u.timeFormat是自己封装的全局改变时间格式函数
// 获取本周日期
getMouthTime(e) {
// 获取当前日期
let currentDate = new Date();
// 获取当前日期的星期几(0-6,其中0代表星期日)
let currentDay = currentDate.getDay();
// 计算距离本周第一天的天数差值
let diff = currentDate.getDate() - currentDay + (currentDay === 0 ? -6 : 1);
if(e == 'month') {
// 获取本月第一天的日期
this.start_date = new Date(currentDate.getFullYear(), currentDate.getMonth(), 1);
// 获取下个月第一天的日期
let nextMonthFirstDay = new Date(currentDate.getFullYear(), currentDate.getMonth() + 1, 1);
// 使用下个月第一天的日期减去一天,得到本月最后一天的日期
this.end_date = new Date(nextMonthFirstDay.getTime() - 1);
} else {
// 计算本周第一天的日期
this.start_date = new Date(currentDate.setDate(diff));
// 计算本周最后一天的日期
this.end_date = new Date(currentDate.setDate(currentDate.getDate() + 6));
}
// this.start_date = this.start_date.toLocaleDateString().replace(/\//g,"-")
this.start_date = this.$u.timeFormat(this.start_date, 'yyyy-mm-dd');
this.end_date = this.$u.timeFormat(this.end_date, 'yyyy-mm-dd');
},