Created
January 26, 2021 20:54
-
-
Save designervoid/13fbaa725033f34f9a21bae31af41f79 to your computer and use it in GitHub Desktop.
Get range of dates between two dates
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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