Skip to content

Instantly share code, notes, and snippets.

@designervoid
Created January 26, 2021 20:54
Show Gist options
  • Save designervoid/13fbaa725033f34f9a21bae31af41f79 to your computer and use it in GitHub Desktop.
Save designervoid/13fbaa725033f34f9a21bae31af41f79 to your computer and use it in GitHub Desktop.
Get range of dates between two dates
// inspired by:
// https://flaviocopes.com/how-to-get-days-between-dates-javascript/
// and modified entry data
const getDatesBetweenDates = (startDate, endDate) => {
let dates = [];
//to avoid modifying the original date
const theDate = new Date(startDate);
while (theDate < endDate) {
dates = [...dates, new Date(theDate)];
theDate.setDate(theDate.getDate() + 1);
}
dates = [...dates, endDate];
return dates;
};
const toYearMonthDayFormat = (dates) => {
return dates.map((date) => date.toISOString().slice(0, 10));
};
const firstDate = new Date("2021-01-26");
const secondDate = new Date("2021-02-02");
const rangeOfDates = getDatesBetweenDates(firstDate, secondDate);
const rangeOfDatesFormat = toYearMonthDayFormat(rangeOfDates);
console.log(rangeOfDatesFormat);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment