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

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

如何将日期增加一天?


当前回答

这个方法更简单, 它会以简单的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); 

将返回相同的结果。

其他回答

我觉得没有什么比. gettime()和. settime()更安全的了,所以这应该是最好的,而且性能也很好。

const d = new Date()
console.log(d.setTime(d.getTime() + 1000 * 60 * 60 * 24)) // MILLISECONDS

. setdate()用于无效的Date(如31 + 1)太危险了,这取决于浏览器的实现。

使用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)以外的值

在遵循其他人的建议之前,你首先需要解析你的字符串:

var dateString = "2010-09-11";
var myDate = new Date(dateString);

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

如果你想让它恢复到相同的格式,你必须“手动”完成:

var y = myDate.getFullYear(),
    m = myDate.getMonth() + 1, // january is month 0 in javascript
    d = myDate.getDate();
var pad = function(val) { var str = val.toString(); return (str.length < 2) ? "0" + str : str};
dateString = [y, pad(m), pad(d)].join("-");

但我建议像其他回复中提到的那样获得Date.js,这将对你有很大帮助。

这个方法更简单, 它会以简单的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); 

将返回相同的结果。

 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