问题描述
给定两个 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)),否则您将结束每个存储的日期都是循环中 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 循环遍历日期范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!





大气响应式网络建站服务公司织梦模板
高端大气html5设计公司网站源码
织梦dede网页模板下载素材销售下载站平台(带会员中心带筛选)
财税代理公司注册代理记账网站织梦模板(带手机端)
成人高考自考在职研究生教育机构网站源码(带手机端)
高端HTML5响应式企业集团通用类网站织梦模板(自适应手机端)