views:

595

answers:

3

How are you currently parsing ISO8601 dates e.g. 2010-02-23T23:04:48Z in JavaScript?

Some browsers return NaN (including Chrome) when using the code below, FF3.6+ works though.

<html>
<body>
  <script type="text/javascript">
  var d = Date.parse("2010-02-23T23:04:48Z");
  document.write(d);
</script>
</body>
</html>

You can try this here http://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_parse

+1  A: 

Try this: http://anentropic.wordpress.com/2009/06/25/javascript-iso8601-parser-and-pretty-dates/

Luca Matteis
ok, that'll work. thanks +1
AlexanderN
A: 

On the question in the title: Not natively (as you've tested :) )

In ECMA-262 (3/e) the only requirement for Date.parse[15.9.4.2] is the round-trip conversion via .toString() and .toUTCString() won't change the Date object, i.e.

 Date.parse(x.toString()) == Date.parse(x.toUTCString()) == x

and both .toString()[15.9.5.2] and .toUTCString()[15.9.5.42] are implementation-dependent, so what format Date.parse can parse is totally unspecified.

KennyTM
A: 

As others have mentioned, it's not in the 3rd edition specification. It is in the 5th edition specification however, and I quote:

ECMAScript defines a string interchange format for date-times based upon a simplification of the ISO 8601 Extended Format. The format is as follows: YYYY-MM-DDTHH:mm:ss.sssZ

So it should be trickling into browsers soon (Microsoft have developed a new JS engine for IE9, it makes sense that it would use ECMA 5th). If you want to implement a solution in the meantime, you might want to optimize so that your script can take advantage of the native if available:

(function ()
{
    if (isNaN(Date.parse("2010-02-23T23:04:48Z")))
    {
        var oldParse = Date.prototype.parse;
        Date.prototype.parse = function (strTime)
        {
           // regex test strTime for ISO 8601, use oldParse if it isn't
           // Use custom parser if it is.
        }
    }
})();
Andy E