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:
- Using push() Method
- Using for loop and push() Method
Approach 1: Using push() Method
- 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) { // Adding the date to array dArray.push( new Date(cDate) + '<br>' ); // Increment the date by 1 day cDate = cDate.addDay(1); } return dArray; } function GFG_Fun() { let startDate = new Date(); // Making lastDate equal to 4 more days // from startDate. let endDate = startDate.addDay(4); console.log(getDate(startDate, endDate)); } GFG_Fun(); |
[ '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; // Date[] keeps all the dates 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(); // Making lastDate equal to 4 more days // from startDate let endDate = startDate.addDay(4); console.log(getDates(startDate, endDate)); } GFG_Fun(); |
[ 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 ]