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