javascriptdatetimegoogle-apps-scripttimezonegoogle-apps-script-editor

Why is the timestamp log one day behind after I parse the timezone out?


I have a variable 'var timeStamp = finalData.obj.followers[0].timestp;' that logs '2020-04-15T00:00:00.000Z.'

I only want the date, and not the timezone, so I used the variable below to parse the data.

I used a new variable 'var formattedDate = Utilities.formatDate(new Date(timeStamp), Session.getScriptTimeZone(), "yyyy-MM-dd");' and this one logs '2020-04-14.' It seems to be working, but it is a day behind. It should log 2020-04-15, as it is in the first log. Is there a way to fix this?

I am using Google Apps Script.


Solution

  • It's very likely that the problem is caused because the value and the Google Apps Script project timezone aren't the same.

    One way to get the right date is by using the following code

    var formattedDate = timeStamp.toString().substr(0,10)
    

    Another way is by using UTC as timezone

    var formattedDate = Utilities.formatDate(new Date(timeStamp), 'UTC', "yyyy-MM-dd");
    

    Related