IE7/IE8中的Javascript JSON日期解析返回NaN

Jos*_*iah 40 javascript date utc internet-explorer-8 internet-explorer-7

我正在从JSON事件源解析日期 - 但日期在IE7/8中显示"NaN":

// Variable from JSON feed (using JQuery's $.getJSON)
var start_time = '2012-06-24T17:00:00-07:00';

// How I'm currently extracting the Month & Day
var d = new Date(start_time);
var month = d.getMonth();
var day = d.getDate();

document.write(month+'/'+day);// "6/24" in most browsers, "Nan/Nan" in IE7/8
Run Code Online (Sandbox Code Playgroud)

我究竟做错了什么?谢谢!

ken*_*bec 67

在旧版浏览器中,您可以编写一个函数来解析字符串.

这个创建一个Date.fromISO方法 - 如果浏览器本身可以从ISO字符串中获取正确的日期,则使用本机方法.

有些浏览器部分正确,但返回错误的时区,所以只检查NaN可能不行.

填充工具:

(function(){
    var D= new Date('2011-06-02T09:34:29+02:00');
    if(!D || +D!== 1307000069000){
        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<L; i++){
                    day[i]= parseInt(day[i], 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;
        }
    }
    else{
        Date.fromISO= function(s){
            return new Date(s);
        }
    }
})()
Run Code Online (Sandbox Code Playgroud)

结果:

var start_time = '2012-06-24T17:00:00-07:00';
var d =  Date.fromISO(start_time);
var month = d.getMonth();
var day = d.getDate();

alert(++month+' '+day); // returns months from 1-12
Run Code Online (Sandbox Code Playgroud)

  • 谢谢你的救星. (3认同)
  • @jackocnr那也花了我一分钟.+将D转换为数字.如果它是有效日期,则与D.getTime()或1307000069000相同.否则,NaN.不是非常可读,但很聪明. (2认同)

小智 25

对于ie7/8,我刚做了:

var ds = yourdatestring;
ds = ds.replace(/-/g, '/');
ds = ds.replace('T', ' ');
ds = ds.replace(/(\+[0-9]{2})(\:)([0-9]{2}$)/, ' UTC\$1\$3');
date = new Date(ds);
Run Code Online (Sandbox Code Playgroud)

这将所有出现的" - "替换为"/",时间标记"T"替换为空格,并将时区信息替换为IE友好字符串,这使得IE7/8能够正确地解析字符串中的日期.为我解决了所有问题.


Est*_*hin 5

看看RobG在toJSON()的结果上的帖子,IE8和IE9 +之间的日期不同.

以下功能在IE 8及以下版本中适用于我.

// parse ISO format date like 2013-05-06T22:00:00.000Z
function convertDateFromISO(s) {
  s = s.split(/\D/);
  return new Date(Date.UTC(s[0], --s[1]||'', s[2]||'', s[3]||'', s[4]||'', s[5]||'', s[6]||''))
}
Run Code Online (Sandbox Code Playgroud)

你可以测试如下:

var currentTime = new Date(convertDateFromISO('2013-05-06T22:00:00.000Z')).getTime();
alert(currentTime);
Run Code Online (Sandbox Code Playgroud)