How to store all dates in an array present in between given two dates in JavaScript?


Sometimes, we require to get all the dates between the given date range. In this tutorial, we will take two dates and find all dates between two dates. Also, we will store all dates in the array.

Here, we will learn three approaches to storing all dates in an array present between given two dates in JavaScript.

Use the while loop and setDate() method

We can use the while loop for iteration and the setDate() method to set dates in the date object. On every iteration of the while loop, we can increase the date by one day and set it to date1.

Syntax

Users can follow the syntax below to use the while loop and setDate() method to get all dates between two dates.

while (date1 <= date2) {
   dateArray.push(new Date(date1));
   date1.setDate(date1.getDate() + 1);
} 

In the above syntax, date1 is the start date, and date2 is the end date.

Algorithm

Step 1 – Create two dates.

Step 2 – Use the while loop, and check if date1 is less than date2.

Step 3 – Create a new date from date1, and push it to the dateArray.

Step 4 – Get the date from the date1 using the getDate() method, and add 1.

Step 5 – Use the setDate() method to set a new date.

Example 1

In the example below, we have created the date1 and date2 using the Date object. After that, we implemented the above algorithm to get all dates between two dates. In the output, users can observe all the dates between date1 and date2.

<html>
<body>
   <h2>Using the <i> setDate() method and while loop</i> to get all dates between two dates in the array format. </h2>
   <div id = "output"></div>
   <script>
      var output = document.getElementById('output');
      var date1 = new Date("2023-01-01");
      var date2 = new Date("2023-01-11");
      output.innerHTML += "The date1 is " + date1 + "<br/>";
      output.innerHTML += "The date2 is " + date2 + "<br/>";
      var dateArray = [];
      while (date1 <= date2) {
         dateArray.push(new Date(date1));
         date1.setDate(date1.getDate() + 1);
      }
      output.innerHTML += "The date array is <br/>";
      for (let i = 0; i < dateArray.length; i++) {
         output.innerHTML += dateArray[i] + " <br/>";
      }
   </script>
</body>
</html>

Use the for loop and total Milliseconds of the date

In this approach, we will get the total milliseconds of the first and second dates. After that, we will keep adding the milliseconds of 1 day to the total milliseconds of the current date and using new milliseconds, and we can create a date.

This way, we can find all dates between the given two dates and store them in the array.

Syntax

Users can follow the syntax below to use the for loop and total milliseconds of the date to get all dates between two dates.

for (var currentMillis = startMillis; currentMillis < lastMillis; currentMillis += milliOf1Day) {
   // pushing updated date to the array
   dateArray.push(new Date(currentMillis));
} 

In the above syntax, milliOf1Day is the total milliseconds of the one day.

Algorithm

Step 1 – Get the totalMilliseconds of the current and last date.

Step 2 – Use the for loop, and initialize the currentMillis variable with the total milliseconds of the start date.

Step 3 – Iterate using the for a loop until we find current milliseconds less than milliseconds of the last date.

Step 4 –Also, add milliseconds of 1 day to the currentMillis.

Step 5 – Create a new date using the currentMillis and push to the dateArray variable in the for a loop.

Example 2

In this example, we have milliOf1Day variable in which we have stored the total milliseconds of 1 day. After that, we used the for loop and millisecond to implement the above algorithm to get all dates between two dates.

<html>
<body>
   <h2>Using the <i> setDate() method and while loop </i> to get all dates between two dates in the array format. </h2>
   <div id = "output"></div>
   <script>
      var output = document.getElementById('output');
      var firstDate = new Date("2022-11-01");
      var secondDate = new Date("2022-11-07");
      function getArrayOfDates(firstDate, secondDate) {
      
         // calculate milli seconds of 1 day
         var milliOf1Day = 24 * 60 * 60 * 1000;
         
         // calculate the total milliseconds of the start and end date
         let startMillis = firstDate * 1;
         let lastMillis = secondDate * 1;
         var dateArray = [];
         
         // In the for-loop, on every iteration, add the total milli seconds of 1 day to current milliseconds, and create a new date
         for (var currentMillis = startMillis; currentMillis < lastMillis;         currentMillis += milliOf1Day) {
            
            // pushing updated date to the array
            dateArray.push(new Date(currentMillis));
         } 
         return dateArray;
      }
      let dates = getArrayOfDates(firstDate, secondDate)
      output.innerHTML += "The firstDate is " + firstDate + "<br/>";
      output.innerHTML += "The secondDate is " + secondDate + "<br/>";
      output.innerHTML += "The date array is <br/>";
      
      // printing the date array
      for (let i = 0; i < dates.length; i++) {
         output.innerHTML += dates[i] + " <br/>";
      }
   </script>
</body>
</html>

Use the momentJS library

The momentJS library allows us to manipulate the date.

Syntax

Users can follow the syntax below to use the momentJS library to get all the dates between two dates.

while (currentDate.add(1, "days").diff(lastDate) < 0) { 
   allDates.push(currentDate.clone().toDate());
}

In the above syntax, we used the add()and diff() methods of the momentJS library.

Example 3

In the example below, we are taking the start and last date from the user. After that, we used the input date and created the date using the momentJS library.

Next, we used the add() method to add one day to the current date. Also, we used the diff() method to get the difference between the current date and the last date.

<html>
<head>
   <script src ="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script>
   <script src = "https://cdnjs.cloudflare.com/ajax/libs/momentrange/4.0.1/moment-range.js"> </script>
</head>
<body>
   <h2>Using the <i> setDate() method and while loop </i> to get all dates between two dates in the array format. </h2>
   <div id="output"> </div>
   <button onclick="getArrayOfDates()"> Get array of Dates</button>
   <script>
      var output = document.getElementById('output');
      function getArrayOfDates() {
         let allDates = [];
         let startDate = prompt("Enter start date in the MM / DD / YYYY format", "09/23/2022");
         let endDate = prompt("Enter end date in the MM / DD / YYYY format ", "10/23/2022");
         
         // create a new date from the custom input
         let currentDate = moment.utc(new Date(startDate)).startOf("day"); 
         let lastDate = moment.utc(new Date(endDate)).startOf("day");
         
         // add one day to the current date and check the difference between the current date and the last date
         while (currentDate.add(1, "days").diff(lastDate) < 0) {
            allDates.push(currentDate.clone().toDate());
         }
         allDates.push(currentDate.clone().toDate());
         output.innerHTML += "The currentDate is " + currentDate + "<br/>";
         output.innerHTML += "The lastDate is " + lastDate + "<br/>";
         output.innerHTML += "The date array is <br/>";
         for (let i = 0; i < allDates.length; i++) {
            output.innerHTML += allDates[i] + " <br/>";
         }
      }
   </script>
</body>
</html>

Updated on: 16-Feb-2023

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements