以下函数在Javascript中将日期添加月份源。它考虑了年度结转和不同的月份长度:
function addMonths(date, months) { var d = date.getDate(); date.setMonth(date.getMonth() + +months); if (date.getDate() != d) { date.setDate(0); } return date;}// Add 12 months to 29 Feb 2016 -> 28 Feb 2017console.log(addMonths(new Date(2016,1,29),12).toString());// Subtract 1 month from 1 Jan 2017 -> 1 Dec 2016console.log(addMonths(new Date(2017,0,1),-1).toString());// Subtract 2 months from 31 Jan 2017 -> 30 Nov 2016console.log(addMonths(new Date(2017,0,31),-2).toString());// Add 2 months to 31 Dec 2016 -> 28 Feb 2017console.log(addMonths(new Date(2016,11,31),2).toString());上面的解决方案涵盖了从比目标月份更长的天数中移动一个月的极端情况。例如。
- 到2020年2月29日增加十二个月(应该是2021年2月28日)
- 在2020年8月31日前增加一个月(应为2020年9月30日)
如果申请时某月的某天发生了变化
setMonth,那么我们知道由于月长的不同,我们已经溢出到下个月。在这种情况下,我们习惯于
setDate(0)移回上个月的最后一天。
注意:此答案的此版本替换了无法正常处理不同月份长度的较早版本(如下)。
var x = 12; //or whatever offsetvar CurrentDate = new Date();console.log("Current date:", CurrentDate);CurrentDate.setMonth(CurrentDate.getMonth() + x);console.log("Date after " + x + " months:", CurrentDate);


