我正在寻找最简单、最干净的方法将X个月添加到JavaScript日期中。

我宁愿不处理一年的滚动,也不愿意自己写函数。

有什么内置的东西可以做到这一点吗?


当前回答

考虑到这些答案中没有一个会在月份变化时解释当年的情况,你可以在下面找到我做的一个答案,它应该可以处理这个问题:

方法:

Date.prototype.addMonths = function (m) {
    var d = new Date(this);
    var years = Math.floor(m / 12);
    var months = m - (years * 12);
    if (years) d.setFullYear(d.getFullYear() + years);
    if (months) d.setMonth(d.getMonth() + months);
    return d;
}

用法:

return new Date().addMonths(2);

其他回答

容易的,简单的

function addMonths(date, months) {date.setMonth(date.getMonth() + months); return date;};

使用它作为

 alert(new Date().toLocaleString()); //will say today
 alert(addMonths(new Date(),12).toLocaleString()); //will say next year, same day and month

考虑到这些答案中没有一个会在月份变化时解释当年的情况,你可以在下面找到我做的一个答案,它应该可以处理这个问题:

方法:

Date.prototype.addMonths = function (m) {
    var d = new Date(this);
    var years = Math.floor(m / 12);
    var months = m - (years * 12);
    if (years) d.setFullYear(d.getFullYear() + years);
    if (months) d.setMonth(d.getMonth() + months);
    return d;
}

用法:

return new Date().addMonths(2);

一个简单的答案可以是:

function addMonthsToDate(date, numMonths){
    // Add months
    date.setMonth(date.getMonth() + numMonths);
    
    // Zero the time component
    date.setHours(0, 0, 0, 0);
    return date;
}

这可以被称为-增加两个月:

console.log(addMonthsToDate(new Date(),2));

有时有用的创建日期由一个操作符,如在BIRT参数

我在1个月前用:

new Date(new Date().setMonth(new Date().getMonth()-1));   

我已经通过使用Moment Js库完成了 参考文献:https://momentjs.com/

   startDate = new Date()
   endDate = moment(startDate).add(2, "Months").format("YYYY-MM-DD")
   endDate= new Date (endDate)