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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11020658/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 04:03:28  来源:igfitidea点击:

Javascript JSON Date parse in IE7/IE8 returns NaN

javascriptdateinternet-explorer-8internet-explorer-7utc

提问by Josiah

I'm parsing a date from a JSON event feed - but the date shows "NaN" in IE7/8:

我正在解析 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

What am I doing wrong? Thanks!

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

回答by kennebec

In older browsers, you can write a function that will parse the string for you.

在较旧的浏览器中,您可以编写一个函数来为您解析字符串。

This one creates a Date.fromISO method- if the browser can natively get the correct date from an ISO string, the native method is used.

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

Some browsers got it partly right, but returned the wrong timezone, so just checking for NaN may not do.

一些浏览器部分正确,但返回了错误的时区,因此仅检查 NaN 可能行不通。

Polyfill:

填充物:

(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);
        }
    }
})()

Result:

结果:

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

回答by fbtb

For ie7/8 i just did:

对于 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);

This replaces all occurrences of "-" with "/", time marker "T" with a space and replaces timezone information with an IE-friendly string which enables IE7/8 to parse Dates from Strings correctly. Solved all issues for me.

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

回答by Estin Chin

See RobG's post at Result of toJSON() on a date is different between IE8 and IE9+.

请参阅 RobG 在Result of toJSON() on a date is different between IE8 and IE9+ 中的帖子。

Below function worked for me in IE 8 and below.

以下功能在 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]||''))
}

You can test like below:

你可以像下面这样测试:

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

回答by gib

I suggest http://momentjs.com/for cross browser date issues.

对于跨浏览器日期问题,我建议http://momentjs.com/

回答by William Smith

@gib Thanks for the suggestion on Moment.js. This small library really helps out with dealing with dates and JavaScript.

@gib 感谢您对 Moment.js 的建议。这个小型库确实有助于处理日期和 JavaScript。

Moment.js solved the problem described in the original question that I was also having. IE8 was displaying JSON ISO dates as NaN when parsed into a new Date() object.

Moment.js 解决了我也遇到的原始问题中描述的问题。当解析为新的 Date() 对象时,IE8 将 JSON ISO 日期显示为 NaN。

Quick solution (include moment.js in your page, or copy the code to your js functions include)

快速解决方案(在您的页面中包含 moment.js,或将代码复制到您的 js 函数中包含)

If you just need to display a date on your page, loaded from a JSON ISO date, do this:

如果您只需要在页面上显示从 JSON ISO 日期加载的日期,请执行以下操作:

order_date = moment(data.OrderDate); //create a "moment" variable, from the "data" object in your JSON function in Protoype or jQuery, etc.

$('#divOrderDate).html(order_date.calendar()); //use Moment's relative date function to display "today", "yesterday", etc.

or

或者

order_date = moment(data.OrderDate); //create a "moment" variable, from the "data" object in your JSON function in Protoype or jQuery, etc.

$('#divOrderDate).html(order_date.format('m/d/YYYY')); //use Moment's format function to display "2/6/2015" or "10/19/2014", etc.  

If you must have a Date() object (say for use with jQuery Components), do the following so successfully populate your JSON provided ISO date. (This assumes you are already inside the function of handling your JSON data.)

如果您必须有一个 Date() 对象(比如与 jQuery 组件一起使用),请执行以下操作以成功填充您的 JSON 提供的 ISO 日期。(这假设您已经在处理 JSON 数据的功能中。)

var ship_date = new Date(moment(data.ShipDate).format('m/d/YYYY'));  //This will successfully parse the ISO date into JavaScript's Date() object working perfectly in FF, Chrome, and IE8.

//initialize your Calendar component with the "ship_date" variable, and you won't see NaN again.