0

This is my first post here, so forgive me if I'm doing this wrong. I am incrementing a year's worth of dates as follows:

for (i = 0; i <= 360; i++){
    bDate.setDate(bDate.getDate() + 1);
    bArray.push([Utilities.formatDate(bDate, "GMT", "M/dd/YYYY")]);
  }

It works just fine until 12/25/2021, at which point Apps Script decides to celebrate New Year's a few days early!!! See below:

[12/22/2021], [12/23/2021], [12/24/2021], [12/25/2021], [12/26/2022], [12/27/2022], [12/28/2022], [12/29/2022], [12/30/2022], [12/31/2022], [1/01/2022], [1/02/2022]

Am I doing something wrong or is this some sort of bug?

Marios
  • 26,333
  • 8
  • 32
  • 52
  • The issue must be related to this question: https://stackoverflow.com/questions/8686331/y-returns-2012-while-y-returns-2011-in-simpledateformat – Marios Feb 01 '21 at 16:57
  • Can you show us what `bDate` looks like? – RayGun Feb 01 '21 at 17:08
  • Sure. I declare bDate and the array right before the code in my question. ```var bArray = []; var bDate = new Date(lastDate); ``` lastDate is a date that is grabbed from a sheet. – Simon Foster Feb 01 '21 at 17:21

2 Answers2

1

Explanation:

This must be a bug which is related in this question.

I know this is not a solution, but a workaround to solve your problem is to manually add the problematic dates, and then let the for loop continue with the rest of the dates.

  • Another important note is to use SpreadsheetApp.getActive().getSpreadsheetTimeZone() because right now you have hardcoded the timezone and this can result in getting wrong days.

Workaround:

function myFunction() {
  const bArray =  
      [[ '12/22/2021' ],
       [ '12/23/2021' ],
       [ '12/24/2021' ],
       [ '12/25/2021' ],
       [ '12/26/2021' ],
       [ '12/27/2021' ],
       [ '12/28/2021' ],
       [ '12/29/2021' ],
       [ '12/30/2021' ],
       [ '12/31/2021' ]];
  const bDate = new Date(2022,0,1);
  for (i = 0; i <= 360 - bArray.length ; i++){
    bArray.push([Utilities.formatDate(bDate, SpreadsheetApp.getActive().getSpreadsheetTimeZone(), "M/dd/YYYY")]);
    bDate.setDate(bDate.getDate() + 1);
  }
  console.log(bArray);
}
Marios
  • 26,333
  • 8
  • 32
  • 52
0

In fact, your error comes from the misusage of the YYYY which should be here yyyy. Y stands for week year and y for year. Please read MisusedWeekYear. And read with more attention the post question given by @somario where the solution is given at the end.