获取过去12个月的年月日

var fill = function (d) {
            return d < 10 ? '0' + d : d.toString();
        };

        var current = new Date();
        var year = current.getFullYear();
        var month = current.getMonth() + 1;
        var days;        
        var calendar = [];
        
        while ((year > current.getFullYear() - 1) || (month > current.getMonth() + 1)) {
            if(month == 2){
                days= year % 4 == 0 ? 29 : 28;
                 
            }
            else if(month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12){
                //月份为:1,3,5,7,8,10,12 时,为大月.则天数为31;
                days= 31;
            }
            else{
                //其他月份,天数为:30.
                days= 30;
                 
            }
            calendar.push(year + '-' + fill(month) + '-' +days);
            month -= 1;
            if (month <= 0) {
                year -= 1;
                month = 12;
            }
        }

        console.log("过去12月的月份为 [" + calendar.join(", ") + ']');

 

posted @ 2018-09-19 10:00  橙子不是orange  阅读(221)  评论(0编辑  收藏  举报