獲取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;//獲取當前月份的日期
if (month>11){
for(var i=0,j=Math.floor(month/12);i<j;i++){
year++;
month -= 12;
}
}
month=parseInt(month+1);
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+ '日';
}
獲取N天后的日期:
var date='2018-09-09';//當前時間或選取時間
var n=7;//選取時間要向前推進的天數
var date1 = new Date(date);
date1.setDate(date.getDate() - n);//獲取七天前date
let year1 = date1.getFullYear();
let month1 = ((date1.getMonth() + 1 < 10 ? '0' + (date1.getMonth() + 1) : date1.getMonth() + 1));
let myDate1 = (date1.getDate() < 10 ? '0' + date1.getDate() : date1.getDate());
let h1 = (date1.getHours() < 10 ? '0' + date1.getHours() : date1.getHours()) + ':00:00';
let startDate = year1 + "-" + month1 + "-" + myDate1 + " " + h1;
console.log(startDate);