0

I'm trying to calculate the dates of the current and the previous 6 days. This should work by simply subtracting 1 from the previous date, so I implemented my current solution like this:

        let currentDay = new Date();
        let nextDay = new Date();
        for (let i = 0; i < 7; i++) {
            nextDay.setDate(currentDay.getDate() - i);
            console.log("i=" + i + "->" + nextDay);
        }

However, this is the output:

i = 0 -> Thu Dec 03 2020 10: 20: 51 GMT + 0100(Central European Standard Time)  //today
i = 1 -> Wed Dec 02 2020 10: 20: 51 GMT + 0100(Central European Standard Time)  //yesterday
i = 2 -> Tue Dec 01 2020 10: 20: 51 GMT + 0100(Central European Standard Time)  //day before yesterday
i = 3 -> Mon Nov 30 2020 10: 20: 51 GMT + 0100(Central European Standard Time)  //3 days ago
i = 4 -> Fri Oct 30 2020 10: 20: 51 GMT + 0100(Central European Standard Time)  //skips an entire month
i = 5 -> Mon Sep 28 2020 10: 20: 51 GMT + 0200(Central European Summer Time)    //skips another month, 2 days and switches to summertime
i = 6 -> Fri Aug 28 2020 10: 20: 51 GMT + 0200(Central European Summer Time)    //skips another month

It worked as expected when running during the end of last month (where the current month was not escaped). It fails as it enters November. I can't seem to find the cause.

Beltway
  • 508
  • 4
  • 17

1 Answers1

1

You're never recreating nextDate from the initial day. Take a look at this:

function addDays(a_oDate: Date, days: number): Date {
  a_oDate.setDate(a_oDate.getDate() + days);
  return a_oDate;
  }

function printLast7Days(a_oDate: Date): void {
  for (let i = 0; i < 7; i++) {
    let nextDay = new Date(a_oDate); // recreate date from the initial date
    addDays(nextDay, -i); // effectively subtracts i days
    console.log("i=" + i + "->" + nextDay.toDateString());
    }
}

printLast7Days(new Date());

Playground

  • Thanks, adding `nextDay = new Date(currentDay);` actually fixed it. I just still can't grasp where my error lies. My solution should: Calculate the constant `currentDay`; Initialize `nextDay` once; set `nextDay` to `currentDay - n * amount`. Shouldn't the result without re-initialization be the same? – Beltway Dec 04 '20 at 07:06
  • @Beltway if `setDate()` recieves a negative number it will switch months, which is fine but - in your case `nextDate` is already in the past month after 4-5 iterations and it will continue to switch months because `nextDate` is never reset to the current date –  Dec 04 '20 at 08:28