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
Release: 2024-11-11 04:06:02
Original
860 people have browsed it

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;
    }
    Copy after login
  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;
    }
    Copy after login

For example:

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

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template