Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
342 views
in Technique[技术] by (71.8m points)

javascript - Result of toJSON() on a date is different between IE8 and IE9+

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

sessionStorage.currentDate = myDate.toJSON();

and then I do this:

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

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)

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

Update:

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 (which is UTC)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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]||''))
}

Assumes the string is UTC.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...