首页 > 解决方案 > 在 Google App 脚本中转换 Unix 时间戳

问题描述

我是 Google App Script 的新手,目前正在做一个项目来帮助自己熟悉它。我的项目有一部分必须将嵌套 JSON 中的 Unix Timestamp 对象转换为人类可读的时间。由于我不知道如何在 Google App 脚本中转换时间戳,因此我查看了文档并找到了“Utilities.formatDate()”。

我尝试在示例时间戳上使用它来查看它是如何工作的,以及它是否可以用于我的需要。因此,我从数据中获取了一个时间戳,并尝试使用此代码对其进行转换。

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

  Logger.log(formattedDate);
  }

它以一个错误结束:

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

我在这里做错了什么?

标签: google-apps-scriptunix-timestamp

解决方案


正如您的错误消息正确描述的那样,没有formatDate(string,string,string). GAS 中存在的formatDate函数接受三个参数,其中第一个是 a Date,第二个和第三个是string's。您的代码的更正可能如下所示:

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);
}

推荐阅读