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

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

如何将日期增加一天?


当前回答

JavaScript日期的时区/夏令时感知日期增量:

function nextDay(date) {
    const sign = v => (v < 0 ? -1 : +1);
    const result = new Date(date.getTime());
    result.setDate(result.getDate() + 1);
    const offset = result.getTimezoneOffset();
    return new Date(result.getTime() + sign(offset) * offset * 60 * 1000);
}

其他回答

JavaScript日期的时区/夏令时感知日期增量:

function nextDay(date) {
    const sign = v => (v < 0 ? -1 : +1);
    const result = new Date(date.getTime());
    result.setDate(result.getDate() + 1);
    const offset = result.getTimezoneOffset();
    return new Date(result.getTime() + sign(offset) * offset * 60 * 1000);
}

不完全确定这是否是一个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

两种方法:

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)

这个方法更简单, 它会以简单的yyyy-mm-dd格式返回日期,就是这个

function incDay(date, n) {
    var fudate = new Date(new Date(date).setDate(new Date(date).getDate() + n));
    fudate = fudate.getFullYear() + '-' + (fudate.getMonth() + 1) + '-' + fudate.toDateString().substring(8, 10);
    return fudate;
}

例子:

var tomorrow = incDay(new Date(), 1); // the next day of today , aka tomorrow :) .
var spicaldate = incDay("2020-11-12", 1); // return "2020-11-13" .
var somedate = incDay("2020-10-28", 5); // return "2020-11-02" .

Note

incDay(new Date("2020-11-12"), 1); 
incDay("2020-11-12", 1); 

将返回相同的结果。

var myDate = new Date();

//add a day to the date
myDate.setDate(myDate.getDate() + 1);