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

Google Sheets单元格日期与今日纯日期比对的简化实现方法问询

简化Google Sheets纯日期比对方法

你从Google Sheets单元格获取的日期值(示例:“22/03/2024”),原代码通过拆分年月日再构造新日期来忽略时分秒做今日比对,确实可以简化,这里提供两种更简便的方案:

方案一:重置时分秒后比较时间戳

直接对日期对象调用setHours()方法,将时分秒毫秒统一置为0,再通过getTime()获取时间戳进行比较(避免直接比较日期对象的引用问题):

// 获取待验证日期并重置时分秒毫秒
const testDate = sheetRaw.getRange(2, 5).getValue();
testDate.setHours(0, 0, 0, 0);

// 获取今日日期并重置时分秒毫秒
const today = new Date();
today.setHours(0, 0, 0, 0);

// 比较时间戳
console.log(testDate.getTime() === today.getTime());

方案二:转为统一日期字符串比较

将日期格式化为YYYY-MM-DD的字符串,直接比较字符串内容:

// 定义日期格式化函数
const formatToDateString = (date) => {
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份从0开始,需补位
  const day = String(date.getDate()).padStart(2, '0');
  return `${year}-${month}-${day}`;
};

// 获取待验证日期与今日日期
const testDate = sheetRaw.getRange(2, 5).getValue();
const today = new Date();

// 比较格式化后的字符串
console.log(formatToDateString(testDate) === formatToDateString(today));

内容的提问来源于stack exchange,提问作者Sébastien Chevin

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.27 17:32:11