如何更改 chrome 日期解析/排序以匹配 ff/ie 日期解析?

How do I change chromes Date-parsing / Sorting to match ff/ie Dateparsing?

所以我在这里遇到了一个非常奇怪的问题,目前我没有想法。

我有以下函数来根据 属性 RowDate 解析和排序 json 对象, 包含具有以下格式的日期字符串:"/Date(1389682861507+0100)/".

orderByDate: function (json) {
    debug('[DataCollection::orderByDate], json before ordering: ', json);

    _.each(json.LineDefinitions, function (line, i) {
        json.LineDefinitions[i].Artifacts.sort(function (a, b) { //Artifacts is an Array of json subobjects containing "RowDate"
            return MyApp.Utils.formatDate(a.RowDate) - MyApp.Utils.formatDate(b.RowDate);
        });
    });
    debug('[DataCollect::orderByDate], json after ordering: ', json);

    return json;
},

这里每个 RowDate 都包含一个与上面给出的字符串类似的字符串(尽管日期不同)。

formatDate-函数如下所示:

MyApp.Utils.formatDate = function (date) {
    var ret;
    if (date instanceof Date) {
        ret = '/Date(' + date.getTime()
            + (date.getTimezoneOffset() <= 0 ? '+' : '-')
            + String(('0000' + ((date.getTimezoneOffset() / 60) * -100)).substr(-4)) + ')/';
    } else {
        ret = new Date(Number(String(date).replace(/(^.*\()|([+-].*$)/g, '')));
    }
    return ret;
};

对于我的问题案例,程序流使用 else 条件。

现在它在 IE10 和 11(原文如此!)和 Firefox 38.0.5 中运行良好,生成的顺序恰到好处。但是在 chrome 的最新稳定版(你没听错)v43.. 中,我在我的 console.log 中得到了错误的排序,导致我的应用程序稍后出现意外行为。

所以我在这里找到了这个帖子:Different values with Date() in Chrome and IE(这里是德国,当地时间可能不同,所以我认为这可能是原因?!)

并尝试使用 momentjs 将 formatDate-else-line 更改为以下内容(后来来到这个项目。我改变的第一件事是在任何地方都使用 momentjs...):

ret = moment.utc(date).toDate();

=> 没有效果,所以我也从 momentjs-docs 尝试了这个:

ret = moment(date, moment.ISO_8601).toDate();

但这似乎也不起作用。目前我没有想法,我希望你们能帮我解决我的问题:如何更改 chromes 日期解析以匹配 ff/ie 解析?还是我脑子里真的有个大疙瘩,其他地方出了问题?

很高兴收到你的来信!

编辑 为了让事情更清楚,我在这里创建了这个 fiddle : http://jsfiddle.net/o3zh2kv4/8/

在 IE 和 firefox 中,输出为:

test1, test8, test2, test9, test3, test10, test4, test11, test5, test12, test6, test13, test7, test14,

这是我想要的进一步逻辑输出。但在 chrome 中,我得到以下信息:

test8, test1, test9, test2, test10, test3, test4, test11, test5, test12, test6, test13, test7, test14,

我不知道为什么会这样。在这里得到一些帮助会很棒!我也需要chrome来更改顺序。

您遇到的问题很可能是因为不同的浏览器(引擎)执行不同的排序算法。

您遇到的差异(乍一看)都集中在没有差异的元素上(例如,从您的排序函数返回 0),因此没有描述确定性排序行为。

要解决此问题,您需要实施自定义排序算法,或引入更多排序标准。

具体来说,未指定自 22.1.3.24 (https://people.mozilla.org/~jorendorff/es6-draft.html#sec-array.prototype.sort),"The elements of this array are sorted. The sort is not necessarily stable (that is, elements that compare equal do not necessarily remain in their original order). If comparefn is not undefined, it should be a function that accepts two arguments x and y and returns a negative value if x < y, zero if x = y, or a positive value if x > y."

在当前的 V8 HEAD 中(在我开始破解之前它可能已经这样了很长一段时间),Array.prototype.sort() 总是使用不稳定的 QuickSort,这意味着不能保证相等值保持与排序前相同的顺序。

有趣的是,源代码中的注释表明我们曾经在小型数组(<=22 个元素)上使用稳定的插入排序,但现在实际上并没有使用该算法。

我建议您进行试验,看看在 spidermonkey 或脉轮中的元素数量较多时,您是否会出现不稳定的排序行为,如果需要,请务必实施您自己的稳定排序。