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


当前回答

我总结了小时和天。。。

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

其他回答

var today = new Date();
var tomorrow = new Date();
tomorrow.setDate(today.getDate()+1);

小心,因为这可能很棘手。当设置明天时,它仅在当前值与今天的年份和月份匹配时有效。然而,通常将日期设置为“32”这样的数字仍然可以很好地将其移动到下一个月。

您可以尝试:

var days = 50;

const d = new Date();

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

这应该很有效。

我对所提出的解决方案的夏令时有问题。

通过改用getUTCDate/setUTCDate,我解决了问题。

// Curried, so that I can create helper functions like `add1Day`
const addDays = num => date => {
  // Make a working copy so we don't mutate the supplied date.
  const d = new Date(date);

  d.setUTCDate(d.getUTCDate() + num);

  return d;
}

感谢Jason的回答,您的回答符合预期,这里是您的代码和AnthonyWJones的便捷格式的混合:

Date.prototype.addDays = function(days){
    var ms = new Date().getTime() + (86400000 * days);
    var added = new Date(ms);
    return added;
}

最简单的解决方案。

Date.prototype.addDays=函数(天){this.setDate(this.getDate()+parseInt(天));返回此;};//然后打电话var newDate=新日期().addDays(2)//+2天console.log(newDate);//或var newDate1=新日期().addDays(-2)//-2天console.log(newDate1);