JS生成当前月份包括最近12个月内的月份

时间:2022-11-26 05:29:38
    var last_year_month = function() {
var result = [];
for(var i = 0; i < 12; i++) {
var d = new Date();
d.setDate(1);
d.setMonth(d.getMonth() - i);
var m = d.getMonth() + 1; m = m < 10 ? "0" + m : m;
//在这里可以自定义输出的日期格式
result.push(d.getFullYear() + "-" + m);
//result.push(d.getFullYear() + "年" + m + '月');
} return result;
}; var time=new Array(); //生成前12个月日期下拉框
for(var allinfo = last_year_month(), i = 0; i < allinfo.length; i++) {
time[i]=allinfo[i];
}

结果:

 ["2019-04", "2019-03", "2019-02", "2019-01", "2018-12", "2018-11", "2018-10", "2018-09", "2018-08", "2018-07", "2018-06", "2018-05"]