1

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;
}
DoneDeal0
  • 5,273
  • 13
  • 55
  • 114
  • Does this answer your question? [Javascript - get array of dates between 2 dates](https://stackoverflow.com/questions/4413590/javascript-get-array-of-dates-between-2-dates) – Hassan Imam Mar 13 '21 at 11:56

2 Answers2

2

What's happening is that you're mutating the startDate that gets passed in. This is a common problem in pass-by-reference languages (look into side effects, etc), but the core of your problem is that each loop you set the start date's date to be i more than it was set to be the previous loop -- hence the strange output.

You have two options here:

  • Add 1 to it each time, rather than i;
  • Don't mutate it at all, but make a new date object each iteration. This is the best option as it means you don't accidentally mutate a date that gets passed in and then used later on.

An example of the second option is shown below:

function get15DaysRange(currentDate){
    return [...Array(15)].map((_,i)=> {
      currentDate = new Date(currentDate); // clone the date object
      currentDate.setDate(currentDate.getDate() + 1); // increment it
      return currentDate;
    })
}
Toastrackenigma
  • 7,604
  • 4
  • 45
  • 55
2

You can basically add 1 day to your startDate and use getDate():

const startDate = new Date("2021-02-26")
const today = new Date("2021-03-13")

while (startDate <= today) {
  console.log(startDate.getDate());
  startDate.setDate(startDate.getDate() + 1);
}

This prompts:

26
27
28
1
2
3
4
5
6
7
8
9
10
11
12
13
Emre Alparslan
  • 1,022
  • 1
  • 18
  • 30