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

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

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


当前回答

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

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

更新:

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

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

其他回答

所有这些看起来都太复杂了,我猜这引发了一场关于增加“一个月”到底是什么意思的争论。是指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));
};

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

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

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

一个简单的答案可以是:

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

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

方法:

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

我写了另一种解决方案,对我来说很好。当您希望计算合同的结束时,它很有用。例如,start=2016-01-15, months=6, end=2016-7-14(即最后一天-1):

<script>
function daysInMonth(year, month)
{
    return new Date(year, month + 1, 0).getDate();
}

function addMonths(date, months)
{
    var target_month = date.getMonth() + months;
    var year = date.getFullYear() + parseInt(target_month / 12);
    var month = target_month % 12;
    var day = date.getDate();
    var last_day = daysInMonth(year, month);
    if (day > last_day)
    {
        day = last_day;
    }
    var new_date = new Date(year, month, day);
    return new_date;
}

var endDate = addMonths(startDate, months);
</script>

例子:

addMonths(new Date("2016-01-01"), 1); // 2016-01-31
addMonths(new Date("2016-01-01"), 2); // 2016-02-29 (2016 is a leap year)
addMonths(new Date("2016-01-01"), 13); // 2017-01-31
addMonths(new Date("2016-01-01"), 14); // 2017-02-28