JS中给指定时间增加月份

function addMonth(){

    var date = "2018-11-30 23:59:59";
    //var date = "2018-11-30";
    var addNum = "3";


    var num = parseInt(addNum);
    var d=new Date(date); 
    
    var thisMonth = d.getMonth()+1;
    var thisYear = d.getFullYear();
    var thisDay = d.getDate();
    var thisHour = d.getHours();
    var thsiMinu = d.getMinutes();
    var thisSecon = d.getSeconds();
    
    var addCount = thisMonth + num;
    var diffMonthCount = parseInt(addCount/12);    //取整
    
    if((thisMonth + num) == 12*diffMonthCount){    //如果是本年
        if((thisMonth + num) == 12){
            diffMonthCount = 0;
        }else{
            diffMonthCount = diffMonthCount-1;
        }
    }
    if(thisMonth + num > 12){    //如果是大于一年
        thisYear += diffMonthCount;
    }
    thisMonth = (addCount)-12*diffMonthCount;
    if(thisMonth < 10){
        thisMonth = "0"+thisMonth;
    }
    if(thisHour < 10){
        thisHour = "0"+thisHour;
    }
    if(thsiMinu < 10){
        thsiMinu = "0"+thsiMinu;
    }
    if(thisSecon < 10){
        thisSecon = "0"+thisSecon;
    }
    
    var thatDate = new Date(thisYear,thisMonth,0); //当天数为0 js自动处理为上一月的最后一天
    var thatDay = thatDate.getDate();//指定年月的当月最大天数
    
    var diffDay = thatDay - thisDay;
    if((thatDay - thisDay) > 0 || (thatDay - thisDay) < 0){
        thisDay = thatDay;
    }
    var dateStr = "";
    if(thsiMinu == 0 && thisSecon == 0){
        dateStr = thisYear + "-" + thisMonth + "-" + thisDay;
    }else{
        dateStr = thisYear + "-" + thisMonth + "-" + thisDay +" " +thisHour+":"+ thsiMinu+":"+thisSecon;
    }
    return dateStr;
    
}

 

你可能感兴趣的:(js操作增加月份的方法)