在JavaScript中增长日期

我须要在JavaScript中将日期值增长一天。 javascript

例如,个人日期值为2010-09-11,我须要将次日的日期存储在JavaScript变量中。 html

如何将日期增长一天? java


#1楼

不能彻底肯定它是否为BUG(已测试Firefox 32.0.3和Chrome 38.0.2125.101),可是如下代码在巴西(-3 GMT)上将失败: git

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+"");

结果: github

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

在日期上增长一个小时,将使其工做完美(但不能解决问题)。 ide

$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毫秒,例如: this

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

#3楼

接下来的5天: spa

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从返回的结果中切片日期值,而后增长所需的天数。 prototype

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();