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

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

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


当前回答

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

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

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

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

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

其他回答

来自@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);

从所给出的许多复杂而丑陋的答案可以看出,日期和时间对于使用任何语言的程序员来说都是一场噩梦。我的方法是将日期和“delta t”值转换为Epoch Time(以毫秒为单位),执行任何算术运算,然后转换回“人类时间”。

// Given a number of days, return a Date object
//   that many days in the future. 
function getFutureDate( days ) {

    // Convert 'days' to milliseconds
    var millies = 1000 * 60 * 60 * 24 * days;

    // Get the current date/time
    var todaysDate = new Date();

    // Get 'todaysDate' as Epoch Time, then add 'days' number of mSecs to it
    var futureMillies = todaysDate.getTime() + millies;

    // Use the Epoch time of the targeted future date to create
    //   a new Date object, and then return it.
    return new Date( futureMillies );
}

// Use case: get a Date that's 60 days from now.
var twoMonthsOut = getFutureDate( 60 );

这是为一个略有不同的用例编写的,但您应该能够轻松地将其用于相关任务。

编辑:完整的源代码在这里!

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

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

所有这些看起来都太复杂了,我猜这引发了一场关于增加“一个月”到底是什么意思的争论。是指30天吗?是从1号到1号的意思吗?从最后一天到最后一天?

如果是后者,那么加一个月到2月27日就会到3月27日,但加一个月到2月28日就会到3月31日(闰年除外,会到3月28日)。那么从3月30日减去一个月…2月27日吗?谁知道……

对于那些寻找简单解决方案的人来说,只需要增加几毫秒就可以了。

function getDatePlusDays(dt, days) {
  return new Date(dt.getTime() + (days * 86400000));
}

or

Date.prototype.addDays = function(days) {
  this = new Date(this.getTime() + (days * 86400000));
};

这适用于所有的边缘情况。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;
}