I need to get an array of days that would represent the range between date A and date B. Exemple:
const startDate = new Date("2021-02-26")
const today = new Date("2021-03-13")
// expected output:
// [26,27,28,1,2,3,4,6,7,8,9,10,11,12,13]
My function is:
function get15DaysRange(startDate){
return [...Array(15)].map((_,i)=> {
const startingDay = startDate.getDate()
const day = startDate.setDate(startingDay + i)
return new Date(day).getDate()
})
}
get15DaysRange("2021-02-26T11:53:04.607Z")
// current output:
// [26,27,1,4,8,13,19,26,3,12,22,3,15,28,11]
How to fix this?
EDIT: based on the two great answers below, I've eventually done a mix of both:
export function getDaysRange(startDate: Date, endDate: Date = new Date()) {
const range = [];
const mutableStartDate = new Date(startDate);
while (mutableStartDate <= endDate) {
range.push(mutableStartDate.getDate());
mutableStartDate.setDate(mutableStartDate.getDate() + 1);
}
return range;
}