如何使用JavaScript将日期添加到当前日期?JavaScript是否有像.NET的AddDay()那样的内置函数?


当前回答

我们的团队认为date fns是这个领域最好的图书馆。它将日期视为不可变的(Moment.js可能永远不会采用不变性),速度更快,可以模块化加载。

const newDate = DateFns.addDays(oldDate, 2);

其他回答

您可以使用以下选项创建一个:-

Date.prototype.addDays=函数(天){var date=新日期(this.valueOf());date.setDate(date.getDate()+天);返回日期;}var date=新日期();console.log(date.addDays(5));

这会在必要时自动增加月份。例如:

8/31+1天将变为9/1。

直接使用setDate的问题是它是一个赋值函数,最好避免这种情况。ECMA认为将Date视为一个可变的类而不是一个不可变的结构是合适的。

为管道运营商设计的解决方案:

const addDays = days => date => {
  const result = new Date(date);

  result.setDate(result.getDate() + days);

  return result;
};

用法:

// Without the pipeline operator...
addDays(7)(new Date());

// And with the pipeline operator...
new Date() |> addDays(7);

如果您需要更多功能,我建议查看日期fns库。

    //the_day is 2013-12-31
    var the_day = Date.UTC(2013, 11, 31); 
    // Now, the_day will be "1388448000000" in UTC+8; 
    var the_next_day = new Date(the_day + 24 * 60 * 60 * 1000);
    // Now, the_next_day will be "Wed Jan 01 2014 08:00:00 GMT+0800"

这类函数有问题,我用parseInt()解决

Date.prototype.addDays = function(dias) {

    var date = new Date(this.valueOf());
    date.setDate(parseInt(date.getDate()) + parseInt(dias));
    return date;
}

Date.prototype.addMonths = function(months) {
    var date = new Date(this.valueOf());
    date.setMonth(parseInt(date.getMonth()) + parseInt(months));
    return date;
}


Date.prototype.addYears = function(years) {
    var date = new Date(this.valueOf());
    date.setFullYear(parseInt(date.getFullYear()) + parseInt(years));
    return date;
}

不,javascript没有内置函数,但是您可以使用一行简单的代码

timeObject.setDate(timeObject.getDate() + countOfDays);