【问题标题】:Date.js parsing an ISO 8601 UTC date incorrectlyDate.js 错误地解析 ISO 8601 UTC 日期
【发布时间】:2012-08-27 16:02:23
【问题描述】:

使用 javascript 库 Date.js 我发现当我将一个 ISO 8601 格式的 UTC 0 日期传递给 Date.parse() 函数时,我得到一个代表相同日期但具有本地时区的对象添加。

例如,

鉴于日期:2012-08-27T14:57:00Z(采用 ISO 8601 格式),显示时间为 14:57 UTC,为什么将其解析为 14:57 GMT-400 而不是 10 :57 GMT-400?

我有created a fiddle 来展示它。

如果确实有错误,或者我对解析结果的理解不正确,请告诉我。

【问题讨论】:

    标签: javascript datejs


    【解决方案1】:

    是的,这是一个错误 - 甚至是 a reported one

    我可以推荐使用Moment.js 库吗?例如this:

    console.log(moment('2012-08-27T14:57:00Z').toString());

    ... 将正确识别给定的 UTC 时间。

    【讨论】:

    • 经过进一步审查,事实证明开发人员不应再使用 Date.js(请参阅此链接 plus.google.com/113127438179392830442/posts/htwWUqxHmUY)。很好的说明,可以引导人们关注时刻。
    • 为什么我以前没有遇到过 Moment.js,优秀的库,很好的调用 @raina77ow :)
    【解决方案2】:

    这似乎是 Date.js 的错误。使用 new Date('2012-08-27T14:57:00Z') 返回正确的日期。

    【讨论】:

    • 事实证明是的,这是 Date.js 中的一个错误。自 2008 年以来,我没有看到任何新的发展,所以我假设它永远不会被修复。感谢您注意到它适用于 new Date(...),因为这将是我暂时使用的修复程序。
    【解决方案3】:

    这是由 DateJS 的非常棒的语法分析器的错误实现引起的。

    基本上旧版本只是检查它是否可以使用内置解析器,新版本尝试使用语法解析但忘记首先尝试原始步骤并且语法解析器无法使用时区(这是一个错误,但不同)。

    用这个替换解析函数:

    $D.parse = function (s) {
        var date, time, r = null;
        if (!s) {
            return null;
        }
        if (s instanceof Date) {
            return s;
        }
    
        date = new Date(Date._parse(s));
        time = date.getTime();
        // The following will be FALSE if time is NaN which happens if date is an Invalid Date 
        // (yes, invalid dates are still date objects. Go figure.)
        if (time === time) {
            return date;
        } else {
            // try our grammar parser
            try {
                r = $D.Grammar.start.call({}, s.replace(/^\s*(\S*(\s+\S+)*)\s*$/, "$1"));
            } catch (e) {
                return null;
            }
            return ((r[1].length === 0) ? r[0] : null);
        }
    };
    

    此处提供了核心代码的更新版本(并将在未来修复未解决的错误):

    https://github.com/abritinthebay/datejs/

    【讨论】:

      猜你喜欢
      • 2013-05-14
      • 1970-01-01
      • 2011-06-17
      • 2021-01-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-15
      相关资源
      最近更新 更多