我需要在JavaScript中增加一天的日期值。
例如,我有一个日期值2010-09-11,我需要将第二天的日期存储在一个JavaScript变量中。
如何将日期增加一天?
我需要在JavaScript中增加一天的日期值。
例如,我有一个日期值2010-09-11,我需要将第二天的日期存储在一个JavaScript变量中。
如何将日期增加一天?
当前回答
通过原生JS,添加一天你可以做以下事情:
let date = new Date(); // today
date.setDate(date.getDate() + 1) // tomorrow
另一种选择是使用矩库:
const date = moment().add(14, "days").toDate()
其他回答
明天在纯JS的一行,但它是丑陋的!
new Date(new Date().setDate(new Date().getDate() + 1))
结果如下:
Thu Oct 12 2017 08:53:30 GMT+0200 (Romance Summer Time)
使用dateObj.toJSON()方法获取日期的字符串值参考:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toJSON 从返回值中切片日期,然后增加所需的天数。
var currentdate = new Date();
currentdate.setDate(currentdate.getDate() + 1);
var tomorrow = currentdate.toJSON().slice(0,10);
未来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)
}
var myDate = new Date();
//add a day to the date
myDate.setDate(myDate.getDate() + 1);
使用这个函数,它解决了我的问题:
let nextDate = (daysAhead:number) => {
const today = new Date().toLocaleDateString().split('/')
const invalidDate = new Date(`${today[2]}/${today[1]}/${Number(today[0])+daysAhead}`)
if(Number(today[1]) === Number(12)){
return new Date(`${Number(today[2])+1}/${1}/${1}`)
}
if(String(invalidDate) === 'Invalid Date'){
return new Date(`${today[2]}/${Number(today[1])+1}/${1}`)
}
return new Date(`${today[2]}/${Number(today[1])}/${Number(today[0])+daysAhead}`)
}