一个日期的toJSON()的结果在IE8和IE9 +之间是不同的 [英] Result of toJSON() on a date is different between IE8 and IE9+

查看:200
本文介绍了一个日期的toJSON()的结果在IE8和IE9 +之间是不同的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在进行从Date到string的转换,并在sessionStorage中使用。
所以我首先这样做:

I'm doing a conversion from Date to string and back for using in sessionStorage. so I first do this:

sessionStorage.currentDate = myDate.toJSON();

然后我这样做:

if (sessionStorage.currentDate ) {
    myDate = new Date(sessionStorage.currentDate);
}

问题是 myDate.toJSON() 函数在 IE9 + 中返回2013-05-06T22:00:00.000Z但在IE8中它返回2013-05-06T22:00:00Z在末尾缺少小数部分。
事实上,在IE8中,后续的重新转换为日期失败(来自 new Date(sessionStorage.currentDate)的结果是 NaN

The problem is that the myDate.toJSON() function in IE9+ returns "2013-05-06T22:00:00.000Z" but in IE8 it returns "2013-05-06T22:00:00Z" missing the decimal part at the end. The fact is that in IE8 is failing the subsequent re-conversion into a date (the result from new Date(sessionStorage.currentDate) is NaN)

任何想法为什么会发生这种情况,以及如何使此代码适用于IE8 +?

Any idea why this is happening and how to make this code work for IE8+?

我试图在调试中替换字符串,结果是两个字符串都不工作。所以它实际上似乎是一个问题,新的Date(sessionStorage.currentDate)不能识别格式(即是UTC)

I tried to replace the string in debug, and it turns out that none of the 2 strings works. So it actually seems to be a problem of the new Date(sessionStorage.currentDate) not recognizing the format (wich is UTC)

推荐答案

在ES5之前,解析日期完全取决于实现。 IE 8(和更低版本)将不会解析ES5中指定的ISO 8601格式,因此只需自行解析:

Prior to ES5, parsing of dates was entirely implementation dependent. IE 8 (and lower) won't parse the ISO 8601 format specified in ES5, so just parse it yourself:

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

假设字符串是UTC。

这篇关于一个日期的toJSON()的结果在IE8和IE9 +之间是不同的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆