JavaScript get days between two dates

Viewed 114

I have two dates Sun Mar 08 2020 05:30:00 GMT+0530 (India Standard Time) Sat Mar 14 2020 05:30:00 GMT+0530 (India Standard Time) when I loop these two dates with condition I want to get the 7 days between the days. But it returns upto friday only.

Below I added my code snippetSomeone help me what went wrong.

getDaysArray = (start, end) => {
    console.log(start,end)
    for (var arr = [], dt = start; dt <= end; dt.setDate(dt.getDate() + 1)) {
      console.log(dt);
      arr.push(new Date(dt.setHours(23, 59, 59, 0)));
    }
    console.log("array=>"+arr)
    return arr;
  };
1 Answers

It's because setHours() modifies the date object, so by setting the hours to just before midnight, the loop condition stops one iteration earlier; you'd need to make a copy first:

getDaysArray = (start, end) => {
    for (var arr = [], dt = start; dt <= end; dt.setDate(dt.getDate() + 1)) {
        let newDate = new Date(dt);
        arr.push(new Date(newDate.setHours(23, 59, 59, 0)));
    }
    return arr;
};
console.log(getDaysArray(new Date('Sun Mar 08 2020 05:30:00 GMT+0530 (India Standard Time)'), new Date('Sat Mar 14 2020 05:30:00 GMT+0530 (India Standard Time)')));

You'd have to do the same thing if you were ever planning to use a generator:

function* getDates(start, end) {
  for (let dt = start; dt <= end; dt.setDate(dt.getDate() + 1)) {
    yield new Date(dt)
  }
}

startDate = new Date('Sun Mar 08 2020 05:30:00 GMT+0530 (India Standard Time)');
endDate = new Date('Sat Mar 14 2020 05:30:00 GMT+0530 (India Standard Time)');

console.log(Array.from(getDates(startDate, endDate), dt => new Date(dt.setHours(23, 59, 59, 0))));

Related