1、获取当前时间
var curDate = new Date() /* 获取当前时间 */
2、获取当前月份和年份
var curMonth = curDate.getMonth()+1 // 这边获取的一月是0,所以要加1
var curYear = curDate.getFullYear()
3、获取当前的时间戳
curDate.setMonth(curMonth)
curDate.setDate(0)
4、然后通过循环获取日期对应的星期
for (var i = 1; i <= curDate.getDate(); i++) {
const d = i > 9 ? i : `0${i}` // 后面解析格式要 yyyy-mm-dd
const day = curYear + '.' + (curMonth + 1) + '.' + d // 获取月份所有天数
// 这里的0--星期天 1~~~6 星期一~星期六
const week =
new Date(day).getDay() == 0 ? '天' : new Date(day).getDay() == 1 ? '一' : new Date(day).getDay() == 2
? '二' : new Date(day).getDay() == 3 ? '三' : new Date(day).getDay() == 4 ? '四' : new Date(day).getDay() == 5
? '五' : new Date(day).getDay() == 6 ? '六' : ''
}
5、最后收割
let monthDays = []
if (item.week == '五') {
var date = new Date(item.day)
monthDays.push(date.getDate())
}
完整代码
var curDate = new Date()
var curMonth = curDate.getMonth() + 1
var curYear = curDate.getFullYear()
curDate.setMonth(curMonth)
curDate.setDate(0)
let days = []
for (var i = 1; i <= curDate.getDate(); i++) {
const d = i > 9 ? i : `0${i}`
const day = curYear + '.' + (curMonth + 1) + '.' + d
const week =
new Date(day).getDay() == 0 ? '天' : new Date(day).getDay() == 1 ? '一' : new Date(day).getDay() == 2
? '二' : new Date(day).getDay() == 3 ? '三' : new Date(day).getDay() == 4 ? '四' : new Date(day).getDay() == 5
? '五' : new Date(day).getDay() == 6 ? '六' : ''
days.push({
day,
week,
})
}
let monthDays = []
days.forEach(item => {
if (item.week == '五') {
var date = new Date(item.day)
monthDays.push(date.getDate())
}
})