背景
火狐浏览器66版本,通过tolocalString()方法,获取的2021-05-20 上午11:30:00类似的格式,导致通过无法转成Date。
解决
const str = "2021-05-20 上午11:30:00";
// 使用正则表达式匹配日期时间信息并提取
const regex = /^(\d{4})-(\d{2})-(\d{2})\s(\S{2})(\d{2}):(\d{2}):(\d{2})$/;
const matches = str.match(regex);
// 将提取到的信息转换为对应的数字,并使用Date对象创建时间对象
const year = parseInt(matches[1]);
const month = parseInt(matches[2]) - 1; // 月份需要减1,因为Date对象月份从0开始计数
const day = parseInt(matches[3]);
const hour = parseInt(matches[4]);
const minute = parseInt(matches[5]);
const second = parseInt(matches[6]);
const date = new Date(year, month, day, hour, minute, second);
修复Firefox66中日期格式转换为Date对象的问题
文章介绍了在Firefox66版本中遇到的通过toLocaleString()方法获取的日期格式(如2021-05-20上午11:30:00)无法直接转换为Date对象的问题。通过使用正则表达式匹配和解析日期时间信息,然后用Date构造函数创建正确的时间对象,从而解决了这个问题。

被折叠的 条评论
为什么被折叠?



