Google脚本-通过表单输入格式化日期

时间:2020-05-19 10:44:43

标签: date google-apps-script google-sheets google-forms

首先,我对此很陌生,但是我目前有一个脚本,该脚本根据对Google表单的输入来输出Google Doc / PDF。

无论何时提交新表格,都会输出PDF,当前日期的格式为DD / MM / YY,但我希望它以dd MMMM yyyy的形式显示,即2020年5月19日,而不是19/05/20。

我尝试使用以下方法更改格式

var signDate = e.values[1];
var formatSignDate = Utilities.formatDate(signDate, "GMT+1", "dd MMMM yyyy");
body.replaceText('{{Execution Date}}', formatSignDate);

但是出现以下错误

异常:参数(字符串,字符串,字符串)与Utilities.formatDate的方法签名不匹配。 在autoFillFromForm(代码:17:28)

我在做什么错?我不能将.formatDate与工作表单元格中的日期一起使用吗?

编辑:带有signDate日志的错误消息

Stackdriver日志信息signDate = 20/05/2020错误异常:参数 (String,String,String)与以下方法的签名不匹配 Utilities.formatDate。在autoFillFromForm(代码:23:34)

1 个答案:

答案 0 :(得分:1)

异常:参数(字符串,字符串,字符串)与Utilities.formatDate的方法签名不匹配

意味着signDate无法正确识别为日期对象

请提供日志signDate,以帮助您更详细地进行故障排除。

更新

如果您使用英国格式(DD / MM / YYYY)的日期字符串,则不会自动将其识别为Javascript date object

您需要对其进行转换,例如:

  var convertedDate = new Date(signDate.split('/')[2], signDate.split('/')[1] - 1, signDate.split('/')[0]);
  Logger.log(convertedDate);
  var formatSignDate = Utilities.formatDate(convertedDate, "GMT+1", "dd MMMM yyyy");
  Logger.log(formatSignDate);

注意:如果将Utilities.formatDate()设置为与脚本时区不同的时区,则如上所述使用//Get the DocumentReference of the parent doc const parentDocId = snapshot.ref.parent.id; 可能会给您错误的日期。