获取最近 30 天的日期(不包括今天)

5 篇文章 0 订阅

获取最近 30 天的日期(不包括今天)格式只有天
想要格式为年月日的参考
原文链接:http://www.childsay.com/js-last-30-dates.html
其实也就在在push的时候把年月加上 比如

dates.push(`${endYear}-${endMonthString}-${item}`);
const _ = require('lodash');
const dayjs = require('dayjs');
const last30dates= ()=> {
    const endDayjs = dayjs();
    const endYear = endDayjs.year();
    const endMonth = endDayjs.month() + 1;
    const endMonthString = endMonth < 10 ? '0' + endMonth.toString() : endMonth.toString();
    const endDate = endDayjs.date();
    const startDayjs = dayjs().subtract(30, 'days');//想包括今天的话30改成29
    const startYear = startDayjs.year();
    const startMonth = startDayjs.month() + 1;
    const startMonthString = startMonth < 10 ? '0' + startMonth.toString() : startMonth.toString();
    const startDate = startDayjs.date();
    const dates = [];
    if (endMonth === startMonth) {
        // 同一个月,直接改变天数
        _.each(_.range(startDate, endDate + 1), (item) => {
            if (item < 10) {
                item = '0' + item.toString();
            }
            dates.push(`${item}`);
        });
    } else if (endMonth === startMonth + 1 || startMonth - endMonth === 11) {
        // 上一个月和当前月
        // 上个月
        _.each(_.range(startDate, startDayjs.daysInMonth() + 1), (item) => {
            if (item < 10) {
                item = '0' + item.toString();
            }
            dates.push(`${item}`);
        });

        // 当前月
        _.each(_.range(1, endDate), (item) => { //想包括今天的话endDate+1
            if (item < 10) {
                item = '0' + item.toString();
            }
            dates.push(`${item}`);
        });
    } else if (endMonth === startMonth + 2) {
        // 上上个月、上个月和当前月,遇到 2 月时
        // 上上个月
        _.each(_.range(startDate, startDayjs.daysInMonth() + 1), (item) => {
            if (item < 10) {
                item = '0' + item.toString();
            }
            dates.push(`${item}`);
        });

        // 2 月
        _.each(_.range(1, startDayjs.add(1, 'months').daysInMonth() + 1), (item) => {
            if (item < 10) {
                item = '0' + item.toString();
            }
            dates.push(`${item}`);
        });

        // 当前月
        _.each(_.range(1, endDate + 1), (item) => {
            if (item < 10) {
                item = '0' + item.toString();
            }
            dates.push(`${item}`);
        });
    }
    console.log(dates)
    return dates;
}

输出
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值