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