Return all dates between two dates in an array in Javascript

Mahabubur Rahman
0

In the previous article, we discuss "how to get date array from given date range in PHP". Today I will show the same solution on javascript.

The task is to give two dates and get an array of dates between two dates.

Solution:

  • Give two dates in SQL formate
  • Convert given dates to date object using js Date() object
  • Check start date lase then end date.
  • Set start date to current date
  • Loop between the current date and end date until the current date equals the end date and push into an array.
  • return the array.

So the expected function is bellow -

function getDates(startDate, stopDate) {

  var dateArray = new Array();

  var currentDate = new Date(startDate);

  while (currentDate <= new Date(stopDate)) {

    let f_current_date = new Date(currentDate);

    dateArray.push(f_current_date.toISOString().split('T')[0]);

    currentDate = currentDate.addDays(1);

  }

  return dateArray;

}


Call the function as - 

getDates('2021-05-01','2021-05-10')


The output will as bellow - 

[

"2021-05-01", 

"2021-05-02",

 "2021-05-03", 

"2021-05-04",

 "2021-05-05",

 "2021-05-06", 

"2021-05-07", 

"2021-05-08", 

"2021-05-09", 

"2021-05-10"

]

So now we get our expected output array.


How to get date array from given date range in PHP


Post a Comment

0Comments
Post a Comment (0)