开发者

Does Javascript/EcmaScript3 support ISO8601 date parsing?

开发者 https://www.devze.com 2022-12-23 06:18 出处:网络
How are you currently parsingISO8601 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.

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开发者_StackOverflow中文版?filename=tryjsref_parse


This is an excellent implementation which covers edge cases and falls back to native implementation. https://github.com/csnover/js-iso8601/


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


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 (IE9, Chrome 1, Firefox 4 are at least some of the browsers supporting ISO 8601 dates). 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.parse;
        Date.parse = function (strTime)
        {
           // regex test strTime for ISO 8601, use oldParse if it isn't
           // Use custom parser if it is.
        }
    }
})();


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号