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

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

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


当前回答

从所给出的许多复杂而丑陋的答案可以看出,日期和时间对于使用任何语言的程序员来说都是一场噩梦。我的方法是将日期和“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 );

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

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

其他回答

从所给出的许多复杂而丑陋的答案可以看出,日期和时间对于使用任何语言的程序员来说都是一场噩梦。我的方法是将日期和“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 );

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

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

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

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

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

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

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

一个简单的答案可以是:

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

我使用moment.js库进行日期-时间操作。 添加一个月的示例代码:

var startDate = new Date(...);
var endDateMoment = moment(startDate); // moment(...) can also be used to parse dates in string format
endDateMoment.add(1, 'months');
var a=new Date();
a.setDate(a.getDate()+5);

如上所述的方法,您可以添加月到日期功能。