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

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

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


当前回答

正如大多数答案突出显示的那样,我们可以使用setMonth()方法和getMonth()方法一起为给定的日期添加特定的月份数。

例子:(@ChadD在他的回答中提到。)

Var x = 12;//或任何偏移量 var CurrentDate = new Date(); CurrentDate.setMonth(CurrentDate.getMonth() + x);

但是我们应该小心地使用这个解决方案,因为我们会在边界情况下遇到麻烦。

要处理边缘情况,下面链接中给出的答案是有帮助的。 https://stackoverflow.com/a/13633692/3668866

其他回答

这适用于所有的边缘情况。newMonth的奇怪计算处理负月份输入。如果新的月份与预期的月份不匹配(比如31 Feb),它会将月份的日期设置为0,这意味着“上个月的结束”:

function dateAddCalendarMonths(date, months) {
    monthSum = date.getMonth() + months;
    newMonth = (12 + (monthSum % 12)) % 12;
    newYear = date.getFullYear() + Math.floor(monthSum / 12);
    newDate = new Date(newYear, newMonth, date.getDate());
    return (newDate.getMonth() != newMonth)
        ? new Date(newDate.setDate(0))
        : newDate;
}

来自@bmpsini和@Jazaret的回复,但没有扩展原型:使用普通函数(为什么扩展本机对象是一种糟糕的做法?)

function isLeapYear(year) { 
    return (((year % 4 === 0) && (year % 100 !== 0)) || (year % 400 === 0)); 
}

function getDaysInMonth(year, month) {
    return [31, (isLeapYear(year) ? 29 : 28), 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][month];
}

function addMonths(date, value) {
    var d = new Date(date),
        n = date.getDate();
    d.setDate(1);
    d.setMonth(d.getMonth() + value);
    d.setDate(Math.min(n, getDaysInMonth(d.getFullYear(), d.getMonth())));
    return d;
}

使用它:

var nextMonth = addMonths(new Date(), 1);

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

方法:

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);

最简单的解决方法是:

const todayDate = Date.now();
return new Date(todayDate + 1000 * 60 * 60 * 24 * 30* X); 

其中X是我们想要增加的月份数。

简单的解决方案:2678400000是31天,单位为毫秒

var oneMonthFromNow = new Date((+new Date) + 2678400000);

更新:

使用这些数据来构建我们自己的函数:

2678400000 - 31天 2592000000 - 30天 2505600000 - 29天 2419200000 - 28天