generate date array from x-date to y-date

44 Views Asked by At

For a calendar i require to generate an array of dates from 2023-01-01 till 2023-01-15. I've tried to generate the array using a loop-over, however I think the code could be much cleaner.

I would've expected javascript to have an getDateArray(new Date(), new Date('2023-01-15')) function but it doesn't.

1

There are 1 best solutions below

0
Deyan On

i came up with the following but don't have the reputation to post it anywhere else.

you can use the third parameter as an interval

function arrayDateRange(start, stop, step) {
    if (step < 1000) return [start, stop];
    return Array.from({ length: (stop - start) / step + 1 }, (value, index) => {
        return new Date(start.getTime() + index * step)
    });
}

arrayDateRange(new Date('2023-01-01'),new Date('2023-01-15'),(1000*60*60*24))