JavaScript Date ISO8601

后端 未结 3 1642
刺人心
刺人心 2021-02-02 12:30

What is the best way to get a Javascript Date object from a string like the following one:

2011-06-02T09:34:29+02:00 ?

I have trouble with the

3条回答
  •  情书的邮戳
    2021-02-02 12:42

    IE 8 and below, and older versions of the other browsers do not implement the ISO Date format. A problem is that some of the browsers do return a date, instead of NaN, just not the correct one.

    You can write your own method, if you want to support them. The time zone is the tricky bit.

    This example will run once and set a Date.fromISO method- if the native method is supported it will use it.

    (function(){
    var D= new Date('2011-06-02T09:34:29+02:00');
    if(isNaN(D) || D.getUTCMonth()!== 5 || D.getUTCDate()!== 2 ||
    D.getUTCHours()!== 7 || D.getUTCMinutes()!== 34){
        Date.fromISO= 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/);
                for(var i= 0, L= day.length; i

提交回复
热议问题