简体   繁体   English

如何将此日期格式转换为 JS 日期?

[英]How to convert this date format to JS Date?

I'm working with a service that provides a weird date format that I just can not figure out an concise way of converting to a JS Date Object.我正在使用一种提供奇怪日期格式的服务,我只是想不出一种简洁的方法来转换为 JS 日期 Object。 I need to perform some logic with the dates which is why I need to convert it.我需要对日期执行一些逻辑,这就是我需要转换它的原因。

The date format returned by the service is like so: 02/Dec/2020:23:58:15 +0000 .服务返回的日期格式如下: 02/Dec/2020:23:58:15 +0000

Any help highly appreciated, thanks in advance任何帮助都非常感谢,在此先感谢

The date parses if you replace the first : with space如果您将第一个:替换为空格,则会解析日期

 const str = "02/Dec/2020:23:58:15 +0000" console.log(new Date(str.replace(/:/," "))); // change only the first colon

For a safer version it seems we need to do this - tested in Safari, Chrome and Firefox为了获得更安全的版本,我们似乎需要这样做 - 在 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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM