我有一个格式如下的数组:
arr = [
{
'thing':'thing',
'thing2':'thing',
'date':'28/07/2014 14:16'
},
{
'thing':'thing',
'thing2':'thing',
'date':'27/07/2014 14:16'
}
]
我想按日期排序(最近一次,或者更确切地说,最近是0指数)
我该怎么做?
更新
类似
arr.sort(function(a,b){
return new Date(b.date) - new Date(a.date);
});
理论上应该工作,但是,我有一个问题,新的date()由于某种原因在数组中的某些项上返回'无效日期',例如:
arr.sort(function(a,b){
console.log(b.date)
console.log(new Date(b.date))
return new Date(b.date) - new Date(a.date);
});
我得到了记录:
09/01/2014 14:23
Mon Sep 01 2014 14:23:00 GMT+0100 (GMT Daylight Time)
23/07/2014 09:04
Invalid Date
23/07/2014 09:04
Invalid Date
09/01/2014 14:23
Mon Sep 01 2014 14:23:00 GMT+0100 (GMT Daylight Time)
最近怎么回事?
答案 0 :(得分:0)
我爱@Phrogz answer:
arr.sort(function(a,b){
// Turn your strings into dates, and then subtract them
// to get a value that is either negative, positive, or zero.
return new Date(b.date) - new Date(a.date);
});
答案 1 :(得分:0)
这应该有用,请检查旧的IE浏览器,我认为它也应该在那里工作 http://jsfiddle.net/9t3Xq/
arr.sort(function(a, b) {
var valueA, valueB;
var dates1 = a.date.split(" ");
var dates2 = b.date.split(" ");
var dates1YMD = dates1[0].split("/");
var dates2YMD = dates2[0].split("/");
var dates1HIS = dates1[1].split(":");
var dates2HIS = dates2[1].split(":");
valueA = new Date(dates1YMD[2], dates1YMD[1], dates1YMD[0], dates1HIS[0], dates1HIS[1]);
valueB = new Date(dates2YMD[2], dates2YMD[1], dates2YMD[0], dates2HIS[0], dates2HIS[1]);
return valueB - valueA;
});