Home >Web Front-end >JS Tutorial >How to Get an Array of Dates Between Two Dates in Javascript?

How to Get an Array of Dates Between Two Dates in Javascript?

Patricia Arquette
Patricia ArquetteOriginal
2024-11-09 12:55:02642browse

How to Get an Array of Dates Between Two Dates in Javascript?

Getting a Date Array between Two Dates in Javascript

Determining the array of date objects for each day between two given dates is a common task when working with dates in Javascript. This array needs to account for month and year boundaries to maintain accuracy.

Implementation:

To achieve this, we can define a function called getDates that takes two date objects as parameters: a starting date and an end date. Within this function:

  1. Initialize an Array to Store Dates: Create an empty array called dateArray to store the date objects for each day.
  2. Initialize Current Date: Set the currentDate variable to the starting date.
  3. Iterate Through Days: Use a while loop to iterate through the days until the currentDate is greater than or equal to the end date.
  4. Push Date to Array: Inside the loop, add a new Date object representing the current date to the dateArray.
  5. Increment Current Date: Increment the currentDate by one day using the addDays method.
  6. Return the Date Array: Once the loop finishes, return the dateArray.

Example Code:

Here's an example of how you can implement the getDates function:

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

This implementation extends the Date prototype with an addDays method for convenience. A live demo can be found at http://jsfiddle.net/jfhartsock/cM3ZU/.

The above is the detailed content of How to Get an Array of Dates Between Two 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