JavaScript Basics

JavaScript Advanced

JavaScript Arrays

JavaScript Functions

JavaScript Objects

JavaScript DOM

JavaScript String

How to get all dates between two dates in JavaScript?

To get all dates between two dates, go through the following steps:

  1. First, create an empty array that will store all the dates between 2 dates.
  2. After that, create a temporary Date object which is equal to the starting date of the range.
  3. Then, increment the temporary Date object by 1 and push the Date object to the array.
  4. Repeat step 3 until all the dates in a range are covered.

Let's understand the process with the help of an example:

Suppose you want to get all the dates between 27th January 2022 and 19th February 2022.

let startDate = new Date(2022, 0, 27);
let endDate = new Date(2022, 1, 19);
let dates = [];

console.log(startDate.toString());
console.log(endDate.toString());

let tempDate = new Date(startDate.getTime());
while(tempDate <= endDate){
  dates.push(new Date(tempDate));
  tempDate.setDate(tempDate.getDate() + 1);
}

If you don't want to include the starting and ending date, then increment the temporary Date object by 1. Also, change <= to <.

let startDate = new Date(2022, 0, 27);
let endDate = new Date(2022, 1, 19);
let dates = [];

console.log(startDate.toString());
console.log(endDate.toString());

let tempDate = new Date(startDate.getTime());
tempDate.setDate(tempDate.getDate() + 1);

while(tempDate < endDate){
    dates.push(new Date(tempDate));
    tempDate.setDate(tempDate.getDate() + 1);
}

Recommended Posts