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


当前回答

试试这个

function addDays(date,days) {        
      var one_day=1000*60*60*24; 
      return new Date(date.getTime()+(days*one_day)).toLocaleDateString(); 
    }

其他回答

我想我也会给出答案:就我个人而言,我喜欢尝试避免无谓的变量声明、方法调用和构造函数调用,因为它们的性能都很昂贵。(当然是合理的)我本打算在@AnthonyWJones给出的答案下留下评论,但考虑得更好。

// Prototype usage...
Date.prototype.addDays = Date.prototype.addDays || function( days ) {
    return this.setTime( 864E5 * days + this.valueOf() ) && this;
};

// Namespace usage...
namespace.addDaysToDate = function( date, days ) {
    return date.setTime( 864E5 * days + date.valueOf() ) && date;
};

// Basic Function declaration...
function addDaysToDate( date, days ) {
    return date.setTime( 864E5 * days + date.valueOf() ) && date;
};

以上内容将尊重DST。这意味着,如果您添加一个跨越夏令时的天数,则显示的时间(小时)将更改以反映这一点。例子:2014年11月2日02:00是夏令时的结束。

var dt = new Date( 2014, 10, 1, 10, 30, 0 );
console.log( dt );                  // Sat Nov 01 2014 10:30:00
console.log( dt.addDays( 10 ) );    // Tue Nov 11 2014 09:30:00

如果你想保留夏令时的时间(所以10:30仍然是10:30)。。。

// Prototype usage...
Date.prototype.addDays = Date.prototype.addDays || function( days ) {
    return this.setDate( this.getDate() + days ) && this;
};

// Namespace usage...
namespace.addDaysToDate = function( date, days ) {
    return date.setDate( date.getDate() + days ) && date;
};

// Basic Function declaration...
function addDaysToDate( date, days ) {
    return date.setDate( date.getDate() + days ) && date;
};

所以,现在你。。。

var dt = new Date( 2014, 10, 1, 10, 30, 0 );
console.log( dt );                  // Sat Nov 01 2014 10:30:00
console.log( dt.addDays( 10 ) );    // Tue Nov 11 2014 10:30:00

这些答案让我感到困惑,我更喜欢:

var ms = new Date().getTime() + 86400000;
var tomorrow = new Date(ms);

getTime()给出了自1970年以来的毫秒数,86400000是一天中的毫秒数。因此,ms包含所需日期的毫秒。

使用毫秒构造函数可以得到所需的日期对象。

我使用的是:

new Date(dateObject.getTime() + amountOfDays * 24 * 60 * 60 * 1000)

节省时间的工作:

new Date(new Date(2014, 2, 29, 20, 0, 0).getTime() + 1 * 24 * 60 * 60 * 1000)

与新年一起工作:

new Date(new Date(2014, 11, 31, 20, 0, 0).getTime() + 1 * 24 * 60 * 60 * 1000)

它可以参数化:

function DateAdd(source, amount, step) {
  var factor = 1;
  if (step == "day") factor = 24 * 60 * 60 * 1000;
  else if (step == "hour") factor = 60 * 60 * 1000;
  ...
  new Date(source.getTime() + amount * factor);
}

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

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库。

Try

var someDate = new Date();
var duration = 2; //In Days
someDate.setTime(someDate.getTime() +  (duration * 24 * 60 * 60 * 1000));

使用setDate()添加日期并不能解决您的问题,请尝试在2月份添加一些天,如果您尝试在其中添加新的天,则不会产生您预期的结果。