Home >Web Front-end >JS Tutorial >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; }
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; }
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));
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!