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

Google Apps Script发邮件时空日期单元格输出随机值如何解决

问题根因

空单元格执行getValue()会返回空字符串,直接传入new Date("")会生成无效Date实例,Utilities.formatDate处理这类无效日期时就会输出无意义的错误日期。
另外你当前写的日期格式符存在错误:DD代表年积日(一年中的第N天)、YYYY是周历周年,不是你需要的dd-mm-yy(两位日-两位月-两位年)格式。

修复代码

先判断单元格值是否有效,空值/无效日期直接返回空字符串,非空时再执行格式化,同时修正格式符:

// 先取原始值,不要直接转Date
var rawFecha = registro.getRange("c16").getValue();
var fechaF = "";
// 校验值为有效日期时才格式化
if (rawFecha instanceof Date && !isNaN(rawFecha.getTime())) {
  // 时区建议用表格自身时区,替换"GMT"为SpreadsheetApp.getActiveSpreadsheet().getSpreadsheetTimeZone()可避免时差偏差
  fechaF = Utilities.formatDate(rawFecha, "GMT", "dd-MM-yy");
}

如果表格有多个日期字段,建议封装成复用函数减少重复代码:

function safeFormatDate(cell, dateFormat = "dd-MM-yy") {
  const cellVal = cell.getValue();
  // 空值/非日期/无效日期统一返回空
  if (!(cellVal instanceof Date) || isNaN(cellVal.getTime())) return "";
  const tz = SpreadsheetApp.getActiveSpreadsheet().getSpreadsheetTimeZone();
  return Utilities.formatDate(cellVal, tz, dateFormat);
}

// 调用示例
const fechaF = safeFormatDate(registro.getRange("c16"));
// 其他日期字段直接传入对应单元格即可
const startDate = safeFormatDate(registro.getRange("c17"));
const endDate = safeFormatDate(registro.getRange("c18"));

异常效果参考:
空单元格格式化后输出无效日期示例

内容的提问来源于stack exchange,提问作者Clown Aspirant

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.30 10:24:13