Result of toJSON() on a date is different between IE8 and IE9+
datetime, internet-explorer-8, javascript, json
Solution
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.
Problem
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)