Javascript - get array of dates between 2 dates

Scott Klarenbach picture Scott Klarenbach · Dec 10, 2010 · Viewed 207.3k times · Source
var range = getDates(new Date(), new Date().addDays(7));

I'd like "range" to be an array of date objects, one for each day between the two dates.

The trick is that it should handle month and year boundaries as well.

Answer

John Hartsock picture John Hartsock · Dec 10, 2010
Date.prototype.addDays = function(days) {
    var date = new Date(this.valueOf());
    date.setDate(date.getDate() + days);
    return date;
}

function getDates(startDate, stopDate) {
    var dateArray = new Array();
    var currentDate = startDate;
    while (currentDate <= stopDate) {
        dateArray.push(new Date (currentDate));
        currentDate = currentDate.addDays(1);
    }
    return dateArray;
}

Here is a functional demo http://jsfiddle.net/jfhartsock/cM3ZU/