获取过去12个月的年份和月份

function formatNumber(value) {
    return (value < 10 ? "0" : "") + value;
}
function GetMonth() {
    let current = new Date();
    let year = current.getFullYear();
    let month = current.getMonth() + 1;
    let calendar = [];
    while (year > current.getFullYear() - 1 ||month > current.getMonth() + 1) {
        calendar.push(year + "-" + formatNumber(month));
        month -= 1;
        if (month <= 0) {
            year -= 1;
            month = 12;
        }
    }
    return calendar;
}
console.log(GetMonth())

  得到的结果是:

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

posted @ 2018-01-31 13:51  Vicky-Rong  阅读(694)  评论(0)    收藏  举报