js获取月内指定星期的日期

这段代码主要展示了如何使用JavaScript获取当前日期、月份、年份以及对应日期的星期。首先获取当前时间,然后得到月份和年份,接着获取当前时间戳。通过循环遍历当前月份的所有日期,并转换为特定格式,同时确定每一天对应的星期。最终筛选出星期五的日期并存储到数组中。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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())
        }
    })
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值