Home >Web Front-end >JS Tutorial >How to Generate an Array of Dates Between Two Given Dates in JavaScript?

How to Generate an Array of Dates Between Two Given Dates in JavaScript?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-11 04:06:02850browse

How to Generate an Array of Dates Between Two Given Dates in JavaScript?

How can I get a Javascript array of dates between two dates?

To generate an array of date objects representing each day between two given dates, you can use the following steps:

  1. Create a function to extend the Date object's functionalities:

    Date.prototype.addDays = function(days) {
        var date = new Date(this.valueOf());
        date.setDate(date.getDate() + days);
        return date;
    }
  2. Create a function to generate an array of dates:

    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;
    }

For example:

var range = getDates(new Date(), new Date().addDays(7));
// range = [<Date object>, <Date object>, ..., <Date object>]

This approach effectively handles month and year boundaries, ensuring that the resulting array accurately represents the date range between the provided start and stop dates.

The above is the detailed content of How to Generate an Array of Dates Between Two Given Dates in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn