我需要在JavaScript中增加一天的日期值。

例如,我有一个日期值2010-09-11,我需要将第二天的日期存储在一个JavaScript变量中。

如何将日期增加一天?


当前回答

明天在纯JS的一行,但它是丑陋的!

new Date(new Date().setDate(new Date().getDate() + 1))

结果如下:

Thu Oct 12 2017 08:53:30 GMT+0200 (Romance Summer Time)

其他回答

不完全确定这是否是一个BUG(测试Firefox 32.0.3和Chrome 38.0.2125.101),但以下代码将在巴西(-3 GMT)失败:

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

$date = new Date(2014, 9, 16,0,1,1);
$date.shiftDays(1);
console.log($date+"");
$date.shiftDays(1);
console.log($date+"");
$date.shiftDays(1);
console.log($date+"");
$date.shiftDays(1);
console.log($date+"");

结果:

Fri Oct 17 2014 00:01:01 GMT-0300
Sat Oct 18 2014 00:01:01 GMT-0300
Sat Oct 18 2014 23:01:01 GMT-0300
Sun Oct 19 2014 23:01:01 GMT-0200

增加一个小时的日期,将使它完美地工作(但不能解决问题)。

$date = new Date(2014, 9, 16,0,1,1);

结果:

Fri Oct 17 2014 01:01:01 GMT-0300
Sat Oct 18 2014 01:01:01 GMT-0300
Sun Oct 19 2014 01:01:01 GMT-0200
Mon Oct 20 2014 01:01:01 GMT-0200
 Date.prototype.AddDays = function (days) {
    days = parseInt(days, 10);
    return new Date(this.valueOf() + 1000 * 60 * 60 * 24 * days);
}

例子

var dt = new Date();
console.log(dt.AddDays(-30));
console.log(dt.AddDays(-10));
console.log(dt.AddDays(-1));
console.log(dt.AddDays(0));
console.log(dt.AddDays(1));
console.log(dt.AddDays(10));
console.log(dt.AddDays(30));

结果

2017-09-03T15:01:37.213Z
2017-09-23T15:01:37.213Z
2017-10-02T15:01:37.213Z
2017-10-03T15:01:37.213Z
2017-10-04T15:01:37.213Z
2017-10-13T15:01:37.213Z
2017-11-02T15:01:37.213Z

通过原生JS,添加一天你可以做以下事情:

let date = new Date(); // today
date.setDate(date.getDate() + 1) // tomorrow

另一种选择是使用矩库:

const date = moment().add(14, "days").toDate()

将当前日期的增量分配给其他变量

 let startDate=new Date();
 let endDate=new Date();    
 endDate.setDate(startDate.getDate() + 1)
 console.log(startDate,endDate)

结果是表示明天日期的字符串。使用new Date()获取今天的日期,使用Date. getdate()和Date. setdate()添加一天,并将Date对象转换为字符串。

  const tomorrow = () => {
      let t = new Date();
      t.setDate(t.getDate() + 1);
      return `${t.getFullYear()}-${String(t.getMonth() + 1).padStart(2, '0')}-${String(
        t.getDate()
      ).padStart(2, '0')}`;
    };
    tomorrow();