Search code examples
google-apps-scriptunix-timestamp

Converting Unix timestamp in Google App scripts


I am new to Google App Script and am currently working on a project to help myself get familiar with it. My project has a part where I have to convert Unix Timestamp objects in nested JSON to human-readable time. As I don't know about converting timestamps in Google App scripts, I looked into the documentation and found "Utilities.formatDate()".

I tried using it on an example timestamp to see how it works and if it can be used for my needs. So I took a timestamp from the data and tried converting it with this code.

 function blah () {
  var tim = "1572401067";
  var formattedDate = Utilities.formatDate(tim, "GMT+5:30", "MM-dd-yyyy HH:mm:ss");

  Logger.log(formattedDate);
  }

It ends with an error saying:

Cannot find method formatDate(string,string,string). (line 3, file "Code")Dismiss

What am I doing wrong here?


Solution

  • As your error message correctly describes, there is no such function as formatDate(string,string,string). The formatDate function that exists in GAS takes three parameters, where the first one is a Date, and the second and third ones are string's. A correction of your code could look like the following:

    function blah() {
      var tim = 1572401067;
      var date = new Date(tim*1000);
      var formattedDate = Utilities.formatDate(date, "GMT+5:30", "MM-dd-yyyy HH:mm:ss");
      Logger.log(formattedDate);
    }