ES5 sort()和日期

时间:2013-03-06 17:10:49

标签: javascript node.js date ecmascript-5

我在数组中有许多对象。对象有一个'time'属性,它是一个日期字符串。

items = [
    {time: "2013-03-01T10:46:11Z"},
    {time: "2013-03-03T10:46:11Z"},
    {time: "2013-03-02T10:46:11Z"}
]

我希望通过'time'属性对数组进行排序。

我已阅读Sort Javascript Object Array By DateJavascript Date Sorting,但我似乎无法将这些解决方案中的任何一个(转换为Date对象或排序为字符串)工作。

我的排序功能:

items.sort(function(first, second){
    return new Date(first.time) < new Date(second.time) ? 1 : -1;
})

测试结果:

items.forEach(function(item){
    console.log(item.time)
})

返回:

2013-03-01T10:46:11Z
2013-03-03T10:46:11Z
2013-03-02T10:46:11Z

3月1日,3月3日,3月2日。我做错了什么?

1 个答案:

答案 0 :(得分:1)

您在比较器功能中调用字段“date”而不是“time”。此外,该函数应返回一个整数,而不是布尔值:

  return new Date(first.time) - new Date(second.time);

这可能不适用于所有浏览器。如果您的所有时间都是世界时,请将它们作为字符串进行比较:

  return first.time > second.time ? 1 : first.time === second.time ? 0 : -1;