Google Sheets App Script如何获取指定格式日期实现正确对比?
问题根因
你的判断逻辑不生效本质是两个比对值的类型不匹配:
- 你通过
Utilities.formatDate生成的today是字符串类型,值为11.11.2021这类格式的文本 - 你通过
dateCell.getValue()拿到的是JS原生Date对象,setNumberFormat仅修改单元格的显示样式,完全不会改变getValue返回值的类型,你在日志里看到的日期文本只是Logger打印Date对象时自动做的格式转换,实际它的valueOf()返回的是毫秒级时间戳数字,和字符串的valueOf()(就是字符串本身)不可能相等。
修复方案
方案1:统一转成同格式字符串比对(最稳妥,避免时区/时分秒干扰)
推荐优先使用表格自身的时区,不要硬编码GMT+1,避免夏令时或地区变更导致的误差,修正后的代码如下:
function isColumn() { // 取表格配置的时区,兼容性更强 const timeZone = SpreadsheetApp.getActiveSpreadsheet().getSpreadsheetTimeZone(); const today = Utilities.formatDate(new Date(), timeZone, 'dd.MM.yyyy'); const ss = SpreadsheetApp.getActiveSpreadsheet(); const s = ss.getSheetByName("Register"); const dateCell = s.getRange(2,3,1,1); // 把单元格拿到的日期也转成相同格式的字符串再比对 const cellDateStr = Utilities.formatDate(dateCell.getValue(), timeZone, 'dd.MM.yyyy'); if (cellDateStr === today) { Logger.log("Today's column exists"); } else { Logger.log("Create today's column"); } }
方案2:统一转成时间戳比对
需要把两个日期的时分秒都清零,保证比对维度一致:
function isColumn() { const timeZone = SpreadsheetApp.getActiveSpreadsheet().getSpreadsheetTimeZone(); // 生成今日0点的Date对象,清空时分秒 const today = new Date(); today.setHours(0,0,0,0); const ss = SpreadsheetApp.getActiveSpreadsheet(); const s = ss.getSheetByName("Register"); const dateCell = s.getRange(2,3,1,1); const cellDate = dateCell.getValue(); // 单元格日期也清空时分秒,避免误差 cellDate.setHours(0,0,0,0); if (cellDate.valueOf() === today.valueOf()) { Logger.log("Today's column exists"); } else { Logger.log("Create today's column"); } }
内容的提问来源于stack exchange,提问作者noquestiontoosilly
相关产品推荐
相关产品推荐

