使用JavaScript遍历日期范围 [英] Loop through a date range with JavaScript
问题描述
给出两个 Date()
对象,其中一个小于另一个,如何在日期之间每天循环?
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?
谢谢!
推荐答案
这是一种通过使用添加一天的方式来实现此目的的方法,如果需要的话,该日期会延续到下个月,而不会浪费毫秒。
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));
}
请注意,如果要存储日期,需要创建一个新的日期(如上,使用 new Date(d)
),否则最终将以每个存储的日期为<$ c $的最终值c> 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屋!