Given two dates and the task is to get the array of dates between the two given dates using JavaScript.
Below are the following approaches:
Select the first and last date and store it in a variable. Check if the start date is less than the stop date then push the current date in an array and increment its value by 1 day. Repeat the above step until currentDate equal to the last date. Example: In this example, the array of dates is determined by the above approach.
Javascript
Date.prototype.addDay = function (days) {
let date = new Date(this.valueOf());
date.setDate(date.getDate() + days);
return date;
}
function getDate(strDate, stpDate) {
let dArray = new Array();
let cDate = strDate;
while (cDate <= stpDate) {
dArray.push(new Date(cDate) + '<br>');
cDate = cDate.addDay(1);
}
return dArray;
}
function GFG_Fun() {
let startDate = new Date();
let endDate = startDate.addDay(4);
console.log(getDate(startDate, endDate));
}
GFG_Fun();
Output [
'Tue Jul 18 2023 18:59:06 GMT+0000 (Coordinated Universal Time)<br>',
'Wed Jul 19 2023 18:59:06 GMT+0000 (Coordinated Universal Time)<br>',
'Thu Jul 20 2023 18:59:06 GMT+0000 (Coordinated Univ...
Approach 2: Using for loop and push() Method
Get the first and last date and store it into a variable. Calculate 1 day equivalent in milliseconds called _1Day. Set a variable equal to the start date, called ms Push ms (milli-seconds) in form of a date in an array and increment its value by _1Day. Repeat the above step until ms is equal to the last date. Example: In this example, the array of dates is determined by the above approach.
Javascript
Date.prototype.addDay = function (days) {
let date = new Date(this.valueOf());
date.setDate(date.getDate() + days);
return date;
};
function getDates(date1, date2) {
let _1Day = 24 * 3600 * 1000;
let dates = [];
for (let ms = date1.getTime(), last = date2.getTime();
ms <= last; ms += _1Day) {
dates.push(new Date(ms));
}
return dates;
}
function GFG_Fun() {
let startDate = new Date();
let endDate = startDate.addDay(4);
console.log(getDates(startDate, endDate));
}
GFG_Fun();
Output [
2023-07-18T19:12:03.831Z,
2023-07-19T19:12:03.831Z,
2023-07-20T19:12:03.831Z,
2023-07-21T19:12:03.831Z,
2023-07-22T19:12:03.831Z
]
Last Updated :
19 Jul, 2023
Like Article
Save Article
Share your thoughts in the comments
Add Your Comment
Please Login to comment...