Borislav Hadzhiev
Tue Jan 18 2022·2 min read
Photo by Vaida Tamošauskaitė
To get all of the dates between 2 dates:
Date
objects.Date
object to the dates array.function getDatesInRange(startDate, endDate) { const date = new Date(startDate.getTime()); const dates = []; while (date <= endDate) { dates.push(new Date(date)); date.setDate(date.getDate() + 1); } return dates; } const d1 = new Date('2022-01-18'); const d2 = new Date('2022-01-24'); console.log(getDatesInRange(d1, d2));
Note: the function above includes the start and end dates in the results array.
If you want to exclude the end date, you can change the line where we used the
while
loop to while (date < endDate) {
. Changing the less than or equals to
to less than excludes the end date from the results.
If you want to exclude the start date as well, use this code snippet instead:
function getDatesInRange(startDate, endDate) { const date = new Date(startDate.getTime()); // ✅ Exclude start date date.setDate(date.getDate() + 1); const dates = []; // ✅ Exclude end date while (date < endDate) { dates.push(new Date(date)); date.setDate(date.getDate() + 1); } return dates; } const d1 = new Date('2022-01-18'); const d2 = new Date('2022-01-24'); console.log(getDatesInRange(d1, d2));
In the code snippet above, we manually added 1
day to exclude the start date
from the results.
getDatesInRange
function takes a start and end date as parameters and returns an array containing all of the dates between them.We created a Date
object that is a clone of startDate
because the
setDate()
method mutates the Date
object in place and it's not a good
practice to mutate function arguments.
The dates
array is there to store all of the Date
objects in the range.
We used a while
loop to iterate over the dates in the range, as long as the
start date is less than or equal to the end date.
Date
objects, they implicitly get converted to a timestamp of the time elapsed between the Unix Epoch (1st of January, 1970) and the given date.The
setDate
method changes the day of the month for the given Date
instance in place.
On each iteration, we set the start date to the next date, until the start date reaches the end date.
while
loop is no longer met and the dates
array is returned from the function.