How to generate dates between two dates in JavaScript

Generate dates between two dates in JavaScript: Hey Folks! In this tutorial, we will understand how to generate dates between two dates in JavaScript. There are certain cases when we need to find out all dates between two given dates. e.g let’s say we have given a date and we need to find the date 3 days after the given date or 400 days after the given date so in such scenarios we need to find dates in between to get the desired result. Let’s understand the concept by some examples:

generate dates between two dates in JavaScript

JavaScript Code to generate dates between two dates in JavaScript

function getDatesBetween(startDate, endDate) {
  const currentDate = new Date(startDate.getTime());

  const dates = [];

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

  return dates;

const date1 = new Date('2022-04-15');
const date2 = new Date('2022-04-30');

allDates = getDatesBetween(date1, date2);





In this illustration, we’ve crafted a function named getDatesBetween() that takes two parameters, namely startDate and endDate. Sandwiched between these two dates are a bunch of dates we want to unveil. So, the mission here is to print out all those dates.

The action kicks off by creating a date object from the startDate, neatly stashing it in a shiny new variable called currentDate. Simultaneously, we’ve birthed a team of dates, corralled within an array aptly named ‘dates.’ Now, the real magic happens within a trusty while loop. The condition is simple: as long as currentDate remains less than or equal to endDate, we keep the loop churning.

With each iteration, the currentDate earns its spot in the ‘dates’ array. A quick date incrementation by 1 (currentDate.setDate(currentDate.getDate() + 1)) ensures the progression through this chronological quest. The loop tirelessly executes until we reach the endDate, at which point the function proudly delivers the populated ‘dates’ array.

To wrap up this date extravaganza, we unfurl the dates using the trusty console.log() function. Voilà!


In the scenario presented here, both the startDate and endDate are part of the final list of dates. However, should you wish to omit the endDate from this list, be sure to tweak the while condition from (currentDate <= endDate) to (currentDate < endDate). Additionally, switch the positions of the two lines within the while loop accordingly.

Write for us
GeekyBeginners articles are written by software geeks like you. If you also would like to contribute to GeekyBeginners by writing paid articles, you can check the write for us page.

Leave a Comment