[javascript] Loop through a date range with JavaScript

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!

This question is related to javascript loops date iteration date-range

The answer is


Based on Tom GullenĀ“s answer.

var start = new Date("02/05/2013");
var end = new Date("02/10/2013");


var loop = new Date(start);
while(loop <= end){
   alert(loop);           

   var newDate = loop.setDate(loop.getDate() + 1);
   loop = new Date(newDate);
}

var start = new Date("2014-05-01"); //yyyy-mm-dd
var end = new Date("2014-05-05"); //yyyy-mm-dd

while(start <= end){

    var mm = ((start.getMonth()+1)>=10)?(start.getMonth()+1):'0'+(start.getMonth()+1);
    var dd = ((start.getDate())>=10)? (start.getDate()) : '0' + (start.getDate());
    var yyyy = start.getFullYear();
    var date = dd+"/"+mm+"/"+yyyy; //yyyy-mm-dd

    alert(date); 

    start = new Date(start.setDate(start.getDate() + 1)); //date increase by 1
}

I think I found an even simpler answer, if you allow yourself to use Moment.js:

_x000D_
_x000D_
// cycle through last five days, today included_x000D_
// you could also cycle through any dates you want, mostly for_x000D_
// making this snippet not time aware_x000D_
const currentMoment = moment().subtract(4, 'days');_x000D_
const endMoment = moment().add(1, 'days');_x000D_
while (currentMoment.isBefore(endMoment, 'day')) {_x000D_
  console.log(`Loop at ${currentMoment.format('YYYY-MM-DD')}`);_x000D_
  currentMoment.add(1, 'days');_x000D_
}
_x000D_
<script src="https://cdn.jsdelivr.net/npm/moment@2/moment.min.js"></script>
_x000D_
_x000D_
_x000D_


Based on Tabare's Answer, I had to add one more day at the end, since the cycle is cut before

var start = new Date("02/05/2013");
var end = new Date("02/10/2013");
var newend = end.setDate(end.getDate()+1);
var end = new Date(newend);
while(start < end){
   alert(start);           

   var newDate = start.setDate(start.getDate() + 1);
   start = new Date(newDate);
}

Based on Jayarjo's answer:

var loopDate = new Date();
loopDate.setTime(datFrom.valueOf());

while (loopDate.valueOf() < datTo.valueOf() + 86400000) {

    alert(loopDay);

    loopDate.setTime(loopDate.valueOf() + 86400000);
}

If you want an efficient way with milliseconds:

var daysOfYear = [];
for (var d = begin; d <= end; d = d + 86400000) {
    daysOfYear.push(new Date(d));
}

Let us assume you got the start date and end date from the UI and stored it in the scope variable in the controller.

Then declare an array which will get reset on every function call so that on the next call for the function the new data can be stored.

var dayLabel = [];

Remember to use new Date(your starting variable) because if you dont use the new date and directly assign it to variable the setDate function will change the origional variable value in each iteration`

for (var d = new Date($scope.startDate); d <= $scope.endDate; d.setDate(d.getDate() + 1)) {
                dayLabel.push(new Date(d));
            }

Here simple working code, worked for me

_x000D_
_x000D_
var from = new Date(2012,0,1);_x000D_
var to = new Date(2012,1,20);_x000D_
    _x000D_
// loop for every day_x000D_
for (var day = from; day <= to; day.setDate(day.getDate() + 1)) {_x000D_
      _x000D_
   // your day is here_x000D_
_x000D_
}
_x000D_
_x000D_
_x000D_


If startDate and endDate are indeed date objects you could convert them to number of milliseconds since midnight Jan 1, 1970, like this:

var startTime = startDate.getTime(), endTime = endDate.getTime();

Then you could loop from one to another incrementing loopTime by 86400000 (1000*60*60*24) - number of milliseconds in one day:

for(loopTime = startTime; loopTime < endTime; loopTime += 86400000)
{
    var loopDay=new Date(loopTime)
    //use loopDay as you wish
}

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to loops

How to increment a letter N times per iteration and store in an array? Angular 2 Cannot find control with unspecified name attribute on formArrays What is the difference between i = i + 1 and i += 1 in a 'for' loop? Prime numbers between 1 to 100 in C Programming Language Python Loop: List Index Out of Range JavaScript: Difference between .forEach() and .map() Why does using from __future__ import print_function breaks Python2-style print? Creating an array from a text file in Bash Iterate through dictionary values? C# Wait until condition is true

Examples related to date

How do I format {{$timestamp}} as MM/DD/YYYY in Postman? iOS Swift - Get the Current Local Time and Date Timestamp Typescript Date Type? how to convert current date to YYYY-MM-DD format with angular 2 SQL Server date format yyyymmdd Date to milliseconds and back to date in Swift Check if date is a valid one change the date format in laravel view page Moment js get first and last day of current month How can I convert a date into an integer?

Examples related to iteration

Is there a way in Pandas to use previous row value in dataframe.apply when previous value is also calculated in the apply? How to loop over grouped Pandas dataframe? How to iterate through a list of dictionaries in Jinja template? How to iterate through an ArrayList of Objects of ArrayList of Objects? Ways to iterate over a list in Java Python list iterator behavior and next(iterator) How to loop through an array containing objects and access their properties recursion versus iteration What is the perfect counterpart in Python for "while not EOF" How to iterate over a JavaScript object?

Examples related to date-range

MySQL query to select events between start/end date SQL Server : fetching records between two dates? How to know if a DateTime is between a DateRange in C# Javascript - get array of dates between 2 dates Loop through a date range with JavaScript PHP: Return all dates between two dates in an array How to check if a date is in a given range?