在JavaScript中增加日期

↘锁芯ラ 提交于 2020-02-27 12:43:28

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

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

如何将日期增加一天?


#1楼

不能完全确定它是否为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

#2楼

最简单的方法是转换为毫秒并添加1000 * 60 * 60 * 24毫秒,例如:

var tomorrow = new Date(today.getTime()+1000*60*60*24);

#3楼

接下来的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)
}

#4楼

使用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楼

为您提供三种选择:

1.仅使用JavaScript的Date对象(不使用库):

我先前对#1的回答是错误的(它增加了24小时,未能考虑到夏时制的转换; Clever Human指出,东部时区到2010年11月7日将失败)。 相反, Jigar的答案是在没有库的情况下执行此操作的正确方法:

var tomorrow = new Date();
tomorrow.setDate(tomorrow.getDate() + 1);

这甚至在一个月(或一年)的最后一天都可以使用,因为JavaScript日期对象对过渡很聪明:

var lastDayOf2015 = new Date(2015, 11, 31); snippet.log("Last day of 2015: " + lastDayOf2015.toISOString()); var nextDay = new Date(+lastDayOf2015); var dateValue = nextDay.getDate() + 1; snippet.log("Setting the 'date' part to " + dateValue); nextDay.setDate(dateValue); snippet.log("Resulting date: " + nextDay.toISOString());
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 --> <script src="//tjcrowder.github.io/simple-snippets-console/snippet.js"></script>

(此答案目前已被接受,因此我无法删除。在被接受之前,我向OP建议他们接受Jigar的答案,但也许他们接受列表中第2或#3项的答案。)

2.使用MomentJS

var today = moment();
var tomorrow = moment(today).add(1, 'days');

(请注意, add会修改您调用的实例,而不是返回新实例,因此today.add(1, 'days')会在today修改。这就是为什么我们从var tomorrow = ...上克隆op的原因。 )

3.使用DateJS ,但是很长一段时间没有更新:

var today = new Date(); // Or Date.today()
var tomorrow = today.add(1).day();
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!