我需要在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)

其他回答

使用vanilla js递增日期年份:

start_date_value = "01/01/2019"
var next_year = new Date(start_date_value);
next_year.setYear(next_year.getYear() + 1);
console.log(next_year.getYear()); //=> 2020

以防有人想增加date (day)以外的值

未来5天:

var date = new Date(),
d = date.getDate(),
m = date.getMonth(),
y = date.getFullYear();


for(i=0; i < 5; i++){
var curdate = new Date(y, m, d+i)
console.log(curdate)
}

两种方法:

1:

var a = new Date()
// no_of_days is an integer value
var b = new Date(a.setTime(a.getTime() + no_of_days * 86400000)

2:类似上述方法

var a = new Date()
// no_of_days is an integer value
var b = new Date(a.setDate(a.getDate() + no_of_days)

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

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

结果如下:

Thu Oct 12 2017 08:53:30 GMT+0200 (Romance Summer Time)
 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