js 获取当月今天之前的日期

本文介绍了如何使用JavaScript编写一个名为`getPastDatesInMonth`的函数,该函数获取给定月份内所有过去的日期,以字符串格式存储在数组中,以便于日期处理和分析。
//当月今天之前的日期
function getPastDatesInMonth() {
    // 获取今天的日期
    const today = new Date();
    today.setHours(0, 0, 0, 0); // 设置时间为当天的午夜 00:00:00

    // 获取当月的第一天
    const firstDayOfMonth = new Date(today.getFullYear(), today.getMonth(), 1);

    // 创建一个数组来存储今天之前的日期
    const pastDates = [];

    // 从第一天开始,直到今天之前的每一天
    for (let date = new Date(firstDayOfMonth); date < today; date.setDate(date.getDate() + 1)) {
        const formattedDate = `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')}`;
        pastDates.push(formattedDate);
    }

    console.log(pastDates)
    return pastDates;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值