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

Apps Script:如何计算当前日期与单元格日期的时间差(日、时、分)

计算在线Excel中当前时间与单元格日期的时间差(日/时/分)

步骤1:获取选中单元格的日期字符串

通过Excel JavaScript API读取选中单元格的dd.mm.yyyy格式日期:

const cellDateStr = await Excel.run(async (context) => {
  const activeSheet = context.workbook.worksheets.getActiveWorksheet();
  const selectedRange = activeSheet.getSelection();
  selectedRange.load("values");
  await context.sync();
  return selectedRange.values[0][0]; // 提取第一个选中单元格的日期字符串
});

步骤2:将dd.mm.yyyy格式转换为JS Date对象

JavaScript的Date构造函数不直接支持dd.mm.yyyy格式,需要手动拆分转换:

// 拆分日、月、年
const [day, month, year] = cellDateStr.split(".");
// 注意JS月份是0起始(0=1月,11=12月),所以月份要减1
const cellDate = new Date(year, month - 1, day);

如果单元格包含时间(比如dd.mm.yyyy hh:mm),需额外处理时间部分:

const [datePart, timePart] = cellDateStr.split(" ");
const [day, month, year] = datePart.split(".");
const [hours, minutes] = timePart.split(":");
const cellDate = new Date(year, month - 1, day, hours, minutes);

步骤3:计算时间差并转换为日、时、分

用Date.now()获取当前时间戳,和单元格日期的时间戳计算差值,再转换为所需单位:

const nowTimestamp = Date.now();
const cellTimestamp = cellDate.getTime();
const timeDiffMs = nowTimestamp - cellTimestamp; // 总毫秒差

// 转换为日、时、分
const totalSeconds = Math.floor(timeDiffMs / 1000);
const totalMinutes = Math.floor(totalSeconds / 60);
const totalHours = Math.floor(totalMinutes / 60);

const days = Math.floor(totalHours / 24);
const hours = totalHours % 24;
const minutes = totalMinutes % 60;

// 输出结果
console.log(`时间差:${days}天 ${hours}时 ${minutes}分`);

注意事项

  • 确保单元格日期格式严格为dd.mm.yyyy,如果分隔符是/或其他,需要调整split的参数
  • 时区问题:Date.now()和new Date()基于本地时区,若Excel日期为UTC,需用Date.UTC(year, month-1, day)创建UTC日期对象后再计算差值

内容的提问来源于stack exchange,提问作者Shamil Nizaev

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 16:33:25