1 回答
TA贡献1111条经验 获得超0个赞
:
如果将第一个替换为空格,则日期将被解析
const str = "02/Dec/2020:23:58:15 +0000"
console.log(new Date(str.replace(/:/," "))); // change only the first colon
为了获得更安全的版本,我们似乎需要这样做 - 在 Safari、Chrome 和 Firefox 中进行了测试
const monthNames = ["jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec"];
const re = /(\d{2})\/(\w{3})\/(\d{4}):(\d{2}):(\d{2}):(\d{2}) (.*)/;
const makeDate = str => {
const [_, dd, mmm, yyyy, hh, min, ss, tz] = str.match(re)
const tzStr = [tz.slice(0, 3), ':', tz.slice(3)].join(''); // make ±hh:mm
const mm = monthNames.indexOf(mmm.toLowerCase()); // English only
const isoString = `${yyyy}-${mm}-${dd}T${hh}:${min}:${ss}${tzStr}`
console.log(isoString)
return new Date(isoString)
};
const str = "02/Dec/2020:23:58:15 +0000"
const d = makeDate(str);
console.log(d)
添加回答
举报