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

如何将innerText获取的日期字符串转为FireFox支持的有效Date对象?

问题原因

Firefox的Date构造器对非标准日期格式的兼容度比Chrome低,你拿到的2021-08-19 08:20:53 AM不属于ECMAScript规范规定的标准日期字符串格式,Chrome做了自定义兼容支持解析,Firefox没有做对应兼容,所以会返回Invalid Date。

解决方案

方案1:简单格式替换(快速适配Firefox)

把日期和时间之间的空格替换为T,转换为接近ISO 8601的格式即可被Firefox识别:

const createDate = "2021-08-19 08:20:53 AM";
const formattedDateStr = createDate.replace(' ', 'T');
const newDate = new Date(formattedDateStr);

方案2:手动拆分解析(全浏览器兼容,推荐)

如果要保证所有浏览器的表现完全一致,建议手动拆分字符串参数生成Date对象,避免不同浏览器的兼容差异:

const createDate = "2021-08-19 08:20:53 AM";
// 拆分日期、时间、上下午标识
const [datePart, timePart, period] = createDate.split(' ');
const [year, month, day] = datePart.split('-').map(Number);
const [hours, minutes, seconds] = timePart.split(':').map(Number);

// 12小时制转24小时制
let adjustedHours = hours;
if (period === 'PM' && hours < 12) adjustedHours += 12;
if (period === 'AM' && hours === 12) adjustedHours = 0;

// 生成Date对象,注意JS月份从0开始计数,所以要减1
const newDate = new Date(year, month - 1, day, adjustedHours, minutes, seconds);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 09:09:04