regexp Parsing ISO-8601

北战南征 提交于 2021-02-04 18:10:07

问题


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.


回答1:


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))?$/

Explained:

  (
    \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).




回答2:


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 or Z, 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.



来源:https://stackoverflow.com/questions/8269349/regexp-parsing-iso-8601

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!