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


当前回答

int days = 1;
var newDate = new Date(Date.now() + days * 24*60*60*1000);

代码笔

var天数=2;var newDate=新日期(Date.now()+天*24*60*60*1000);document.write(“今日:<em>”);document.write(new Date());document.write('</em><br/>新建:<strong>');document.write(newDate);

其他回答

我总结了小时和天。。。

Date.prototype.addDays = function(days){
    days = parseInt(days, 10)
    this.setDate(this.getUTCDate() + days);
    return this;
}

Date.prototype.addHours = function(hrs){
    var hr = this.getUTCHours() + parseInt(hrs  , 10);
    while(hr > 24){
      hr = hr - 24;
      this.addDays(1);
    }

    this.setHours(hr);
    return this;
}

Try

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

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

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

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

您可以尝试:

var days = 50;

const d = new Date();

d.setDate(d.getDate() + days)

这应该很有效。

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

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视为一个可变的类而不是一个不可变的结构是合适的。