js 当前日期增加自然月

js 在日期不满足的情况下就会自动加1个月,比如在当前时间为3月31号,传入1,1两个参数,预期结果为2月29日,但是结果输出了3月2日。就是如果不满就会溢出到下个月,后来看了api发现了setMonth有两个方法,另外一个是指定月份,指定某一天,就可以解决这个问题

我们先看看按天数去计算的代码,很简单

var d = new Date();

d.setMonth(d.getMonth() +1);

alert(d.toLocaleString());

但是我们要求的是自然月,所以需要判断 是否2月 且是否是闰年 ,我们还需要另外一个方法去格式化时间 ,代码如下

//求自然月日期
        function getMonthBeforeFormatAndDay(num, format, day) {
            var date = new Date();
            date.setMonth(date.getMonth() + (num*1), 1);
            //读取日期自动会减一,所以要加一
            var mo = date.getMonth() + 1;
            //小月
            if (mo == 4 || mo == 6 || mo == 9 || mo == 11) {
                if (day > 30) {
                    day = 30
                }
            }
            //2月
            else if (mo == 2) {
                if (isLeapYear(date.getFullYear())) {
                    if (day > 29) {
                        day = 29
                    } else {
                        day = 28
                    }
                }
                if (day > 28) {
                    day = 28
                }
            }
            //大月
            else {
                if (day > 31) {
                    day = 31
                }
            }

            retureValue = date.format('yyyy' + format + 'MM' + format + day);

            return retureValue;
        }

        //JS判断闰年代码
        function isLeapYear(Year) {
            if (((Year % 4) == 0) && ((Year % 100) != 0) || ((Year % 400) == 0)) {
                return (true);
            } else { return (false); }
        }

        //日期格式化
        Date.prototype.format = function (format) {
            var o = {
                "M+": this.getMonth() + 1, // month
                "d+": this.getDate(), // day
                "h+": this.getHours(), // hour
                "m+": this.getMinutes(), // minute
                "s+": this.getSeconds(), // second
                "q+": Math.floor((this.getMonth() + 3) / 3), // quarter
                "S": this.getMilliseconds()
                // millisecond
            }

            if (/(y+)/.test(format))
                format = format.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
            for (var k in o)
                if (new RegExp("(" + k + ")").test(format))
                    format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length));
            return format;
        }

这样就大功告成啦,网上好像没有这方面的代码,希望能帮到需要求自然月的同学

原文地址:https://www.cnblogs.com/linyijia/p/6118835.html