JavaScript循环在日期范围之间 [英] Javascript loop between date ranges

查看:122
本文介绍了JavaScript循环在日期范围之间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定两个Date()对象,其中一个小于另一个,我如何在日期之间每天循环?

  for(loopDate = startDate; loopDate< endDate; loopDate + = 1)
{

}

这种循环是否有效?但是如何在循环计数器中添加一天?



谢谢!

解决方案>

这是一种方法,通过使用添加一天的方式可以使日期滚动到下个月,如果需要,并且毫不费劲。夏令时也不是问题。

  var now = new Date(); 
var daysOfYear = []; (var d = new Date(2012,0,1); d< = now; d.setDate(d.getDate()+ 1)){
daysOfYear.push(new Date d));
}

请注意,如果要存储日期,需要制作一个新的(如上面的 new Date(d)),否则你会得到每个存储的日期为最终值 d 在循环中。


Given two Date() objects, where one is less than the other, how do I loop every day between the dates?

for(loopDate = startDate; loopDate < endDate; loopDate += 1)
{

}

Would this sort of loop work? But how can I add one day to the loop counter?

Thanks!

解决方案

Here's a way to do it by making use of the way adding one day causes the date to roll over to the next month if necessary, and without messing around with milliseconds. Daylight savings aren't an issue either.

var now = new Date();
var daysOfYear = [];
for (var d = new Date(2012, 0, 1); d <= now; d.setDate(d.getDate() + 1)) {
    daysOfYear.push(new Date(d));
}

Note that if you want to store the date, you'll need to make a new one (as above with new Date(d)), or else you'll end up with every stored date being the final value of d in the loop.

这篇关于JavaScript循环在日期范围之间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆