Create an array of Dates between start date and end date in JavaScript

JavaScript Code

Next →

In this tutorial we will be creating an array of Dates between a start date and an end date using JavaScript.

Start and End Dates

Create two variables that will hold the start date and the end date in the following format YYYY-MM-DD where, YYYY is for the year, MM is the month and DD is the date.

Sample values

YYYY = 2017

MM = 01-12

DD = 01-31

// start and end date
var
  startDate = new Date("2017-10-01"),
  endDate = new Date("2017-10-07");

Function to create the date array

Now we create the function that will return the date array which will hold all the dates from the startDate till the endDate.

// date array
var getDateArray = function(start, end) {

  var
    arr = new Array(),
    dt = new Date(start);

  while (dt <= end) {
    arr.push(new Date(dt));
    dt.setDate(dt.getDate() + 1);
  }

  return arr;

}

Call the getDateArray( ) function

Now we will call the getDateArray() function and it will return an array containing all the dates from start date till the end date.

var dateArr = getDateArray(startDate, endDate);

Complete Code

var startDate = new Date("2017-10-01"); //YYYY-MM-DD
var endDate = new Date("2017-10-07"); //YYYY-MM-DD

var getDateArray = function(start, end) {
    var arr = new Array();
    var dt = new Date(start);
    while (dt <= end) {
        arr.push(new Date(dt));
        dt.setDate(dt.getDate() + 1);
    }
    return arr;
}

var dateArr = getDateArray(startDate, endDate);

// Output
document.write("<p>Start Date: " + startDate + "</p>");
document.write("<p>End Date: " + endDate + "</p>");
document.write("<p>Date Array</p>")
for (var i = 0; i < dateArr.length; i++) {
    document.write("<p>" + dateArr[i] + "</p>");
}

Output

Start Date: Sun Oct 01 2017 05:30:00 GMT+0530 (IST)

End Date: Sat Oct 07 2017 05:30:00 GMT+0530 (IST)

Date Array

Sun Oct 01 2017 05:30:00 GMT+0530 (IST)

Mon Oct 02 2017 05:30:00 GMT+0530 (IST)

Tue Oct 03 2017 05:30:00 GMT+0530 (IST)

Wed Oct 04 2017 05:30:00 GMT+0530 (IST)

Thu Oct 05 2017 05:30:00 GMT+0530 (IST)

Fri Oct 06 2017 05:30:00 GMT+0530 (IST)

Sat Oct 07 2017 05:30:00 GMT+0530 (IST)
Next →