其他分享
首页 > 其他分享> > JS 获取当前时间N个月前的日期

JS 获取当前时间N个月前的日期

作者:互联网

getMonthsAgo: function (monthNum) {
                    debugger;
                    var date = new Date();
                    var year = date.getFullYear();
                    var month = date.getMonth() + 1;
                    month = month < 10 ? '0' + month : month;
                    var day = date.getDate();
                    var days = new Date(year, month, 0);
                    day = day < 10 ? ('0' + day) : day;
                    //days = days.getDate();
                    var year2 = year;
                    var month2 = parseInt(month) - monthNum;
                    if (month2 <= 0) {
                        var a = Math.abs(month2);//取绝对值
                        year2 = parseInt(year2) - parseInt(monthNum / 12 <= 1 ? 1 : (a >= 12 ? Math.ceil(parseInt(monthNum) / 12) : Math.floor(parseInt(monthNum) / 12)));
                        month2 = 12 - (Math.abs(month2) % 12);
                    }
                    var day2 = day;
                    var days2 = new Date(year2, month2, 0);
                    days2 = days2.getDate();//获取当前日期中月的天数 2月只有28
                    if (day2 > days2) {
                        day2 = days2;
                    }
                    if (month2 < 10) {
                        month2 = '0' + month2;
                    }
                    var t2 = year2 + '-' + month2 + '-' + day2 + ' 00:00:00';
                    return t2;
                }

标签:12,month2,month,获取,日期,var,JS,day,parseInt
来源: https://www.cnblogs.com/codeRookie/p/16265311.html