js获取前几个月的数组方法和后几个月的数组方法

//获取month的数组,形如[202003,202004,202005],如果没有指定参考年月,以当前年月为准
//入参,第一个,前几个月;第二个,参考月份如202007,如果没有以当前年月为准
export function getPreMonths(monthNum, endYearMonth) {
    let now = new Date();
    let currentYear = new String(now.getFullYear());
    let currentMonth = addZero(now.getMonth() + 1);

    let end = ""; //结束年月为给定年月或者当前年月
    let endYear = "";
    let endMonth = "";

    if (endYearMonth) {
        end = endYearMonth;
        endYear = endYearMonth.slice(0, 4);
        endMonth = endYearMonth.slice(4, 6);
    } else {
        end = currentYear + currentMonth;
        endYear = currentYear;
        endMonth = currentMonth;
    }

    let result = [];

    for (let i = 0; i < monthNum; i++) {
        let re = "";
        let tempMonth = parseInt(endMonth) - i;
        if (tempMonth <= 0) {
            tempMonth = tempMonth + 12;
            endMonth = parseInt(endMonth) + 12;
            endYear--;
        }

        re = endYear + "" + addZero(tempMonth);
        result.unshift(re);
    }
    return result;
}

export function getNextMonths(monthNum, startYearMonth) {
    let now = new Date();
    let currentYear = new String(now.getFullYear());
    let currentMonth = addZero(now.getMonth() + 1);

    let start = ""; //开始年月为给定年月或者当前年月
    let startYear = "";
    let startMonth = "";

    if (startYearMonth) {
        start = startYearMonth;
        startYear = startYearMonth.slice(0, 4);
        startMonth = startYearMonth.slice(4, 6);
    } else {
        start = currentYear + currentMonth;
        startYear = currentYear;
        startMonth = currentMonth;
    }

    let result = [];

    for (let i = 0; i < monthNum; i++) {
        let re = "";
        let tempMonth = parseInt(startMonth) + i;
        if (tempMonth > 12) {
            tempMonth = tempMonth - 12;
            startMonth = parseInt(startMonth) + 12;
            startYear++;
        }

        re = startYear + "" + addZero(tempMonth);
        result.unshift(re);
    }
    return result;
}
function addZero(num) {
    return num < 10 ? "0" + num : num;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值