简体   繁体   English

ES5 sort()和日期

[英]ES5 sort() and dates

I have a number of objects in an array. 我在数组中有许多对象。 The objects have a 'time' property which is a date string. 这些对象具有“时间”属性,该属性是日期字符串。

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

I wish to sort the array by that 'time' property. 我希望按“时间”属性对数组进行排序。

I've read Sort Javascript Object Array By Date and Javascript Date Sorting , but I can't seem to make either of these solutions (either converting to Date objets or sorting as strings) work. 我已经阅读了按日期对Javascript对象数组进行排序和对Javascript日期排序进行排序 ,但是我似乎无法使这两种解决方案(转换为Date对象或按字符串排序)都可以使用。

My sort function: 我的排序功能:

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

Testing the results: 测试结果:

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

Returns: 返回值:

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

March 1, March 3, March 2. What am I doing wrong? 3月1日,3月3日,3月2日。我在做什么错?

You're calling the field "date" instead of "time" in your comparator function. 您在比较器函数中将字段称为“日期”而不是“时间”。 Also, the function should return an integer, not a boolean: 同样,该函数应返回一个整数,而不是布尔值:

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

That may not work in all browsers. 可能并非在所有浏览器中都适用。 If all your times are Universal Time, just compare them as strings: 如果您所有的时间都是世界时间,只需将它们作为字符串进行比较:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM