獲取n個月後的日期

var months=6;//幾個月後
    var effectDate='2018年8月31日';//任意時間
    var time=effectDate.replace(/年/g,"-").replace(/月/g,"-").replace(/日/g,"");
    var newTime=monthChange(time,months);//獲取的幾個月後時間
    console.log(newTime);
    /*獲取n個自然月後的日期
    * date:當前任意日期
    * num:月數
    * */
    function monthChange(date,num) {
        var newDate=new Date(date);
        var year = newDate.getFullYear();
        var month = newDate.getMonth() + num+1;//獲取當前月份的日期
        if (month>12){
            for(var i=0,j=Math.floor(month/12);i<j;i++){
                year++;
                month -= 12;
            }
        }
        if(month<10){
            month="0"+month;
        }
        var date2=new Date(year,month,0);//新的年月
        var day1=newDate.getDate();
        var day2=date2.getDate();
        if(day1>day2){  //防止+6月後沒有31天
            day1=day2;
        }
        return year + '-' + month + '-' + day1;
    }

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章