需求:获取最近六个月的月份列表,倒序排列。
function getLast6Months(){
var last6Months = [];
var today = new Date();
var year = today.getFullYear();
today.setMonth(today.getMonth());
for(var i=5;i>=0;i--){
last6Months[5-i] = today.getFullYear() +"-"+ fillZero(Number(today.getMonth())+1,2);//这里+1是因为js 的月份是0-11
if(today.getMonth == 0){
today.setFullYear(Number(year)-1);
}
today.setMonth(Number(today.getMonth()-1));
}
return last6Months;
}
//补零操作,保证月份为1位的时候补充前置0
function fillZero(num,fill){
var len = ('' + num).length;
return (Array(fill > len ? fill - len + 1 || 0 : 0).join(0) + num);
}
运行结果:
[
"2024-01",
"2023-12",
"2023-11",
"2023-10",
"2023-09",
"2023-08"
]