Search code examples
javascriptgoogle-apps-scriptdatejs

Error while pushing Dates to Array in Apps Script


This is the function (I feel I did the same thing a few hours ago and the output was what I was expecting)

function errorFunction() {
  let master = []

  let a = [1,2] //a simple array to loop over

  a.forEach(function(b) {
    let theDate = Date.today() // 8th Sep 2021
    let i = 0
    while (i<2) {
      theDate = Date.parse(theDate).addDays(1)
      Logger.log(theDate) // dates are alternating between 9th and 10th september
      master.push([b,i,theDate])

      i = i+1
    }

  })
  
  Logger.log(master) // all dates are 10th september
}

The code is pushing 9th September and 10th September to the array. But the output of the array has only 10th September.

What I expect :

[
  [1.0, 0.0, Fri Sep 9 00:00:00 GMT+05:30 2021],
  [1.0, 1.0, Fri Sep 10 00:00:00 GMT+05:30 2021],
  [2.0, 0.0, Fri Sep 9 00:00:00 GMT+05:30 2021],
  [2.0, 1.0, Fri Sep 10 00:00:00 GMT+05:30 2021]
]

The Output I get :

[
  [1.0, 0.0, Fri Sep 10 00:00:00 GMT+05:30 2021],
  [1.0, 1.0, Fri Sep 10 00:00:00 GMT+05:30 2021],
  [2.0, 0.0, Fri Sep 10 00:00:00 GMT+05:30 2021],
  [2.0, 1.0, Fri Sep 10 00:00:00 GMT+05:30 2021]
]

I am using the latest version of DateJs library.


Solution

  • If you pass a Date object to the parse() method of DateJS, it will return the object (link), and the addDate() method also does not create a new object (link). So while you created a new theDate object for every b value, you modified the same object in the while loop, and put references to it into the master array.

    The solution is to create a new Date object every time you modify theDate. For example, change this line:

    theDate = Date.parse(theDate).addDays(1)
    

    ...to this:

    theDate = new Date(theDate.valueOf()).addDays(1)
    

    ...or this (DateJS defines a clone() method):

    theDate = theDate.clone().addDays(1)
    

    This will clone the theDate object before adding 1 day to it.