regexp解析ISO-8601 [英] regexp Parsing ISO-8601
问题描述
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:哪些浏览器支持使用Date.parse解析ISO-8601日期字符串
处理 2011-11-24T09:00:27 + 0200
目前仅应处理ISO日期的 2011-11-24T09:00:27Z
版本
It currently only is supposed to handle the 2011-11-24T09:00:27Z
version of the ISO date
即
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一起使用
to make this fiddle work with IE and Safari
更新:答案奏效.现在,我可以帮助其他人解析从facebook API返回的ISO日期.
UPDATE: The answers worked. Now I can help others parse the ISO date returned from the facebook API.
推荐答案
要使其与格式为 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:
/^(\d{4}\-\d\d\-\d\d([tT][\d:\.]*)?)([zZ]|([+\-])(\d\d):?(\d\d))?$/
解释:
(
\d{4}\-\d\d\-\d\d # date
([tT][\d:\.]*)? # optional time
)
(
[zZ] # UTC time zone
| # or
([+\-]) # offset sign
(\d\d) # hour offset
:? # optional delimiter
(\d\d) # minute offset
)? # time zone is optional
其余代码无需进行任何更改,并且该功能以前支持的所有格式仍将起作用(与先前的答案不同,它会打破四位数的偏移量).
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).
这篇关于regexp解析ISO-8601的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!