You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Google Apps Script中Utilities.formatDate函数年份转换异常求助

问题根源与解决方案

问题出在你使用的日期格式符 YY 上——在Google Apps Script的Utilities.formatDate中,YY代表ISO周年份(即日期所在周对应的年份),而非自然年份的后两位。

2023年12月31日按照ISO周规则,属于2024年的第1周,因此用YY会返回24;而12月30日仍属于2023年的最后一周,所以YY返回23,这和你日志里的结果完全对应。

解决方法

将格式字符串中的YY替换为yy,yy才是自然年份的最后两位数字(符合你的需求):

function test() {
  var sdate = responses.getItemResponses()[3].getResponse();//date from the form
  Logger.log(sdate);
  // 把YY改成yy,获取自然年份后两位
  Logger.log(Utilities.formatDate(new Date(sdate), Session.getScriptTimeZone(), "yy-MM-dd"));
  Logger.log(Utilities.formatDate(new Date("December 30, 2023"), Session.getScriptTimeZone(), "yy-MM-dd"));
  Logger.log(new Date(sdate).getFullYear().toString().slice(-2));
}

修改后,2023年12月31日的转换结果会是23-12-31,和你通过getFullYear().slice(-2)得到的结果一致。

如果你需要dd-MM-YY格式,同样要把YY换成yy,即格式字符串改为dd-MM-yy。

内容的提问来源于stack exchange,提问作者Pamir Int'l Agencies

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.03 06:07:49