获取周一到周日的具体日期数组,代码如下
mounted() {
console.log(this.getWeekDates())
},
methods: {
// 获取周一到周日的具体日期数组
getWeekDates() {
const d = this.getMonDate()
let arr = []
for (let i = 0; i < 7; i++) {
arr.push([
this.toTimeFormat(d.getFullYear() + '-' + (d.getMonth() + 1 + '-' + d.getDate())),
this.getDayName(d.getDay()),
])
// 格式可以自己修改
d.setDate(d.getDate() + 1)
}
return arr
},
// 日期格式处理函数(自动补零) 输出类型(YYYY-)MM-DD
toTimeFormat(d) {
const arr = d.split('-') // 分解
arr.forEach((item, index) => {
arr[index] = item < 10 ? '0' + item : item // 补零
})
return arr.join('-') // 合并
},
// 获取当前星期一的日期对象
getMonDate() {
let d = new Date()
const day = d.getDay() // 周几,
const date = d.getDate() // 几号
if (day == 1) return d
if (day == 0) d.setDate(date - 6)
else d.setDate(date - day + 1)
return d
},
// 0-6转换成中文名称
getDayName(day) {
const _day = parseInt(day)
if (isNaN(_day) || _day < 0 || _day > 6) return false
const weekday = ['周日', '周一', '周二', '周三', '周四', '周五', '周六']
return weekday[_day]
},
}