Does Javascript/EcmaScript3 support ISO8601 date parsing?

后端 未结 4 714
生来不讨喜
生来不讨喜 2020-12-01 18:57

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 cod

相关标签:
4条回答
  • 2020-12-01 19:08

    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 讨论(0)
  • 2020-12-01 19:24

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

    0 讨论(0)
  • 2020-12-01 19:26

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

    0 讨论(0)
  • 2020-12-01 19:32

    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.
            }
        }
    })();
    
    0 讨论(0)
提交回复
热议问题