Home > Web Front-end > JS Tutorial > How to Generate an Array of Dates Within a Given Range in JavaScript?

How to Generate an Array of Dates Within a Given Range in JavaScript?

Mary-Kate Olsen
Release: 2024-11-09 08:12:02
Original
242 people have browsed it

How to Generate an Array of Dates Within a Given Range in JavaScript?

Generating an Array of Dates within a Given Range in JavaScript

In JavaScript, you may encounter the need to create an array of dates between two specified dates. This can be a challenging task, especially when dealing with month and year boundaries.

To address this issue, let's explore a solution using JavaScript's Date object.

Custom Extension for Adding Days to a Date

First, we'll extend the Date prototype to include an addDays() method. This method takes the number of days to add to the date and returns a new Date object reflecting the adjusted date.

Date.prototype.addDays = function(days) {
    var date = new Date(this.valueOf());
    date.setDate(date.getDate() + days);
    return date;
}
Copy after login

Function to Get an Array of Dates

Next, we'll define a function called getDates() that takes two Date objects as parameters: a startDate and a stopDate.

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

Implementation

This function initializes an empty array called dateArray. It then starts with the startDate and moves forward one day at a time using the addDays() method until it reaches or surpasses the stopDate. For each valid date, it adds a new Date object to the dateArray.

The following code demonstrates the usage of these functions:

var range = getDates(new Date(), new Date().addDays(7));
Copy after login

This code creates an array of Date objects representing the days between today and 7 days from today, including today. The range variable will contain an array of date objects.

Demo

You can try out this solution at http://jsfiddle.net/jfhartsock/cM3ZU/ for a functional demo.

The above is the detailed content of How to Generate an Array of Dates Within a Given Range 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