我需要在JavaScript中增加一天的日期值。
例如,我有一个日期值2010-09-11,我需要将第二天的日期存储在一个JavaScript变量中。
如何将日期增加一天?
我需要在JavaScript中增加一天的日期值。
例如,我有一个日期值2010-09-11,我需要将第二天的日期存储在一个JavaScript变量中。
如何将日期增加一天?
当前回答
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
其他回答
两种方法:
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,添加一天你可以做以下事情:
let date = new Date(); // today
date.setDate(date.getDate() + 1) // tomorrow
另一种选择是使用矩库:
const date = moment().add(14, "days").toDate()
最简单的方法是转换为毫秒,然后加上1000*60*60*24毫秒,例如:
var tomorrow = new Date(today.getTime()+1000*60*60*24);
结果是表示明天日期的字符串。使用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();
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