【问题标题】:How to format the date in Google Sheets using Apps Script?如何使用 Apps 脚本格式化 Google 表格中的日期?
【发布时间】:2019-06-14 09:09:14
【问题描述】:
我正在使用 Google Apps 脚本在 Google 表格中创建自定义报告。我放入 Google 表格的数据来自我正在解析的 JSON 数据。我的一个列包含来自 JSON 的日期和时间字符串,我想对其进行格式化,以便 Google 表格将其识别为日期和时间,而不是而不是一个字符串。
目前,该字符串在 Google 表格中显示如下:
2019-06-10T22:00:00.000Z
我不确定如何更改格式,使其看起来像正确的日期和时间。
编辑:我希望它看起来像:
10-Jun HH-MM
【问题讨论】:
标签:
javascript
google-apps-script
【解决方案1】:
要求:
在 Google Apps 脚本中格式化日期字符串。
解决办法:
将日期字符串传递给日期构造函数new Date(),然后使用Utilities.formatDate 对其进行正确格式化。
示例:
function convertDate() {
var sh = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
var date = sh.getRange(1,1).getValue(); //this is your value '2019-06-10T22:00:00.000Z'
var d = Utilities.formatDate(new Date(date),'GMT+0','dd-MMM HH-mm');
Logger.log(d);
//logger returns: 10-Jun 22-00
}
参考资料:
-
new Date() 用于日期构造函数。
-
Utilities.formatDate() 用于在 Google Apps 脚本中格式化日期。