//计算近半年时间 let nowDate = new Date(); let array = []; let year = nowDate.getFullYear(); let mon = nowDate.getMonth() + 1; for (let i = 0; i < 6; i++) { mon = mon - 1; if (mon <= 0) { year = year - 1; mon = mon + 12; } if (mon < 10) { mon = "0" + mon; } array[i] = year + "-" + mon; }
console.log(array); //["2020-12", "2020-11", "2020-10", "2020-09", "2020-08", "2020-07"]
同理,把 for 循环中的 6,改成 11,即:获取当前月份,再加上往前推的11个月,共12个月,为近1年的时间(可跨年)。
console.log(arrays);
console.log(arrays.pop());
获取最终月份:arrays.pop();