js 日期加指定月份

Date.prototype.AddMonth = function(addnum){
    
    var year = this.getYear(); //获取当前日期的年份
    var month = this.getMonth()+1; //获取当前日期的月份
    var day = this.getDate(); //获取当前日期的日
    //alert(year + ";" + month + ";" + day);
    var month2 = month + addnum; //  5 + -20  = -15 -3 9   
    var y = month2 / 12 ; 
    var m = month2 % 12; 
    if (month2 > 0) {
        year +=  m==0 ? y-1 : y ;
        month =  m==0 ? 12 : m ;
    } else {
        year -= m == 0 ? Math.abs(y) + 1 : Math.abs(y);
        month = (12 + m);
    }
    year = Math.floor(year);
    var date = new Date(year+"/"+month+"/"+day);
    year = date.getYear(); //获取当前日期的年份
    month = date.getMonth()+1; //获取当前日期的月份
    day = date.getDate(); //获取当前日期的日
    //alert(year + ";" + month + ";" + day);
}


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;
}

发表评论

您的电子邮箱地址不会被公开。