使用 JavaScript 循环遍历日期范围 [英] Loop through a date range with JavaScript

查看:34
本文介绍了使用 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)),否则您将结束每个存储的日期都是循环中 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天全站免登陆