Loop through a date range with JavaScript

后端 未结 10 780
情话喂你
情话喂你 2020-11-30 17:46

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

for(loopDate = startDate; loopDate < e         


        
10条回答
  •  无人及你
    2020-11-30 18:33

    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.

提交回复
热议问题