处理异常格式下时间串无法转换成Date对象问题

背景

火狐浏览器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);

你可能感兴趣的:(工作问题,前端,javascript,开发语言)