JavaScript获取最近几个月的年月

var date_list = [];
//第一个参数传递日期,第二个参数传递num,及要返回最近的年月, 第三个参数传递一个数组用于保存日期,第四个参数固定不变
getLastMonthYestdy(new Date(),6, date_list, true);
// console.log(date_list);
$scope.dateTypeList = date_list;
$scope.dateType = $scope.dateTypeList[0];

//获取最近六个月的日期如 ["2019年04月", "2019年03月", "2019年02月", "2019年01月", "2018年12月", "2018年11月"]
function getLastMonthYestdy(da, num, date_list, flag) {

    var date = new Date(da);

    var daysInMonth = new Array([0], [31], [28], [31], [30], [31], [30], [31], [31], [30], [31], [30], [31]);
    var strYear = date.getFullYear();
    var strDay = date.getDate();
    var strMonth = date.getMonth() + 1;

    if (flag === true){
        strMonth = strMonth > 9 ? strMonth : "0"+strMonth;
        var str = strYear+"年"+strMonth+"月";
        date_list.push(str);
    }

    if (strYear % 4 === 0 && strYear % 100 !== 0) {//一、解决闰年平年的二月份天数   //平年28天、闰年29天//能被4整除且不能被100整除的为闰年
        daysInMonth[2] = 29;
    }

    if (strMonth - 1 === 0) //二、解决跨年问题
    {
        strYear -= 1;
        strMonth = 12;
    } else {
        strMonth -= 1;
    }

    // strDay = daysInMonth[strMonth] >= strDay ? strDay : daysInMonth[strMonth];
    strDay = Math.min(strDay, daysInMonth[strMonth]);   //三、前一个月日期不一定和今天同一号,例如3.31的前一个月日期是2.28;9.30前一个月日期是8.30

    //给个位数的月、日补零
    if (strMonth < 10){
        strMonth = "0" + strMonth;
    }

    if (strDay < 10) {
        strDay = "0" + strDay;
    }

    var datastr = strYear + "-" + strMonth + "-" + strDay;
    var datastr1 = strYear.toString() + "年" + strMonth.toString() + "月";

    date_list.push(datastr1);
    num -= 1;

    if (num > 1){
        getLastMonthYestdy(datastr, num, date_list, false)
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值