正则表达式解析 ISO-8601
作为我试图帮助解决的问题的后续: chrome 和其他浏览器中的 javascript date.parse 差异
我需要帮助来更新我在此处找到的正则表达式:
JavaScript:哪些浏览器支持使用 Date.parse 解析 ISO-8601 日期字符串
来处理 2011-11-24T09:00 :27+0200
它目前只应该处理2011-11-24T09:00:27Z
版本的 ISO 日期
rx
function(s){
var day, tz,
rx= /^(\d{4}\-\d\d\-\d\d([tT][\d:\.]*)?)([zZ]|([+\-])(\d\d):(\d\d))?$/,
p= rx.exec(s) || [];
if(p[1]){
day= p[1].split(/\D/).map(function(itm){
return parseInt(itm, 10) || 0;
});
day[1]-= 1;
day= new Date(Date.UTC.apply(Date, day));
if(!day.getDate()) return NaN;
if(p[5]){
tz= parseInt(p[5], 10)*60;
if(p[6]) tz += parseInt(p[6], 10);
if(p[4]== "+") tz*= -1;
if(tz) day.setUTCMinutes(day.getUTCMinutes()+ tz);
}
return day;
}
return NaN;
}
,即用于制作 这个小提琴适用于 IE 和 Safari
更新:答案有效。现在我可以帮助其他人解析从 facebook API 返回的 ISO 日期。
As a followup to a question I am trying to help with: javascript date.parse difference in chrome and other browsers
I need assistance in updating the regex I found here:
JavaScript: Which browsers support parsing of ISO-8601 Date String with Date.parse
to handle 2011-11-24T09:00:27+0200
It currently only is supposed to handle the 2011-11-24T09:00:27Z
version of the ISO date
i.e. the rx in
function(s){
var day, tz,
rx= /^(\d{4}\-\d\d\-\d\d([tT][\d:\.]*)?)([zZ]|([+\-])(\d\d):(\d\d))?$/,
p= rx.exec(s) || [];
if(p[1]){
day= p[1].split(/\D/).map(function(itm){
return parseInt(itm, 10) || 0;
});
day[1]-= 1;
day= new Date(Date.UTC.apply(Date, day));
if(!day.getDate()) return NaN;
if(p[5]){
tz= parseInt(p[5], 10)*60;
if(p[6]) tz += parseInt(p[6], 10);
if(p[4]== "+") tz*= -1;
if(tz) day.setUTCMinutes(day.getUTCMinutes()+ tz);
}
return day;
}
return NaN;
}
to make this fiddle work with IE and Safari
UPDATE: The answers worked. Now I can help others parse the ISO date returned from the facebook API.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
要使其适用于
2011-11-24T09:00:27+0200
格式的日期,只需在最后一个:
之后添加?
,例如:解释:
代码的其余部分不需要任何更改,并且该函数以前支持的所有格式仍然有效(与之前的答案不同,它破坏了四位数字的偏移量)。
To make it work with dates of the format
2011-11-24T09:00:27+0200
simply add a?
after the last:
, eg:Explained:
Rest of the code shouldn't need any changes, and all previously supported formats by the function will still work (unlike the previous answer, which breaks four digit offsets).
我不确定你想要什么,但你的正则表达式是错误的,请尝试更改结尾,使其看起来像这样
/^(\d{4}\-\d\d\-\d\d([tT] [\d:\.]*)?)([zZ]|([+\-])(\d{3}))?$/
它至少会匹配你正在寻找的内容。原始正则表达式查找字符,
z
或Z
,或者+
或-
后跟 2数字,一个冒号,然后是另外 2 个数字,我更改了它,所以它不再寻找 2 个数字,一个冒号和另外 2 个数字,而是像您在示例中那样寻找 3 个数字。I'm not sure what you want but your regex is wrong, try changing the end so it looks like this
/^(\d{4}\-\d\d\-\d\d([tT][\d:\.]*)?)([zZ]|([+\-])(\d{3}))?$/
and it will at least match what you're looking for.The original regex looked for a char, either
z
orZ
, or a+
or a-
followed by 2 digits, a colon and then 2 more digits, I changed it so instead of looking for 2 digits, a colon and 2 more digits it looked for 3 digits as you have in your example.