我需要在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()
其他回答
使用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)以外的值
不完全确定这是否是一个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
使用这个函数,它解决了我的问题:
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}`)
}
明天在纯JS的一行,但它是丑陋的!
new Date(new Date().setDate(new Date().getDate() + 1))
结果如下:
Thu Oct 12 2017 08:53:30 GMT+0200 (Romance Summer Time)
你有三个选择:
1. 仅使用JavaScript的Date对象(没有库):
我之前对第一个问题的回答是错误的(它增加了24小时,没有考虑到日光节约时间的转换;Clever Human指出,它将在东部时区的2010年11月7日失效)。相反,Jigar的答案是在没有库的情况下做到这一点的正确方法:
// To do it in local time
var tomorrow = new Date();
tomorrow.setDate(tomorrow.getDate() + 1);
// To do it in UTC
var tomorrow = new Date();
tomorrow.setUTCDate(tomorrow.getUTCDate() + 1);
这甚至适用于一个月(或一年)的最后一天,因为JavaScript date对象在翻转方面很聪明:
//本地时间 var lastDayOf2015 =新的日期(2015,11,31); console.log(" 2015年最后一天:" + lastDayOf2015.toISOString()); var nextDay =新的日期(+lastDayOf2015); var dateValue = nextDay.getDate() + 1; console.log("将日期部分设置为" + dateValue "); nextDay.setDate (dateValue); console.log("结果日期:" + nextDay.toISOString());
2. 使用MomentJS:
var today = moment();
var tomorrow = moment(today).add(1, 'days');
(注意,add会修改调用它的实例,而不是返回一个新实例,所以今天。Add (1, 'days')将修改为今天。这就是为什么我们开始克隆var明天= ....)
3.使用DateJS,但它没有更新很长一段时间:
var today = new Date(); // Or Date.today()
var tomorrow = today.add(1).day();