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

使用xlsx包读取Excel日期显示为前一天的问题求助

解决xlsx读取Excel日期时的35秒偏差问题

这种固定35秒的日期偏移是早期Excel跨平台(Windows/Mac)日期系统遗留的兼容性问题,xlsx库的cellDates选项在处理时未完全修正该偏差,导致日期被推前一天。以下是几种直接有效的解决方法:

方法1:读取后手动修正偏移量

针对已读取的Date对象,直接加上35秒修正偏差,再按需处理时区:

// 定义修正函数
const fixDateOffset = (date) => {
  if (!(date instanceof Date)) return date;
  return new Date(date.getTime() + 35 * 1000);
};

// 处理读取到的数据数组
const processedData = rawData.map(item => ({
  ...item,
  dob: fixDateOffset(item.dob),
  startDate: fixDateOffset(item.startDate)
}));

// 验证修正后的UTC日期
console.log(moment(processedData[0].dob).tz("UTC").format("YYYY-MM-DD")); // 输出2000-12-01

方法2:关闭自动转日期,手动解析数值

关闭cellDates选项,读取Excel原生日期数值后手动转换,同时修正偏移:

// 调整读取选项
const readFile = xlsx.read(fileStored.Body, {
  cellDates: false,
  cellNF: true
});

// Excel日期数值转JS日期(处理1900闰年bug+35秒偏移)
const excelToJsDate = (excelNum) => {
  const offset = excelNum >= 60 ? 2 : 1; // 修正1900年非闰年bug
  const baseDate = new Date(1900, 0, 1);
  const jsDate = new Date((excelNum - offset) * 86400000 + baseDate.getTime());
  jsDate.setSeconds(jsDate.getSeconds() + 35); // 修正35秒偏移
  return jsDate;
};

// 转换工作表数据
const sheetName = readFile.SheetNames[0];
const rawSheetData = xlsx.utils.sheet_to_json(readFile.Sheets[sheetName]);
const processedData = rawSheetData.map(item => ({
  ...item,
  dob: excelToJsDate(item.dob),
  startDate: excelToJsDate(item.startDate)
}));

方法3:用Moment直接修正偏移

如果项目中已使用Moment.js,可在解析后直接添加35秒:

const correctedDob = moment(rawDate).add(35, 'seconds');
// 输出目标时区的正确日期
console.log(correctedDob.tz("UTC").format("YYYY-MM-DD")); // 2000-12-01

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 15:39:20