问题是 Safari 和其他提到的浏览器(iphone 上的 chrome)无法解析您传递给构造函数的输入字符串。这导致Invalid Date
哪个原语值是NaN
因此,排序函数不能按预期工作,比较return (NaN > NaN) ? 1 : (NaN < NaN) ? -1 : 0;
,导致return 0
为了解决这个问题,以最少的解析工作,我想只是将字符串拆分为-|:|T|\+
. 并自行使用日期部分来构造一个new Date
注意:不幸的是 var d = Date.apply([year,month,...]) 之类的事情是不可能的
所以这是一个在 Safari 上对我有用的排序功能
var dates = [{
name: "A",
created_time: '2013-06-05T08:05:06+0000'
}, {
name: "B",
created_time: '2013-06-03T10:05:06+0000'
}, {
name: "C",
created_time: '2013-06-03T01:05:06+0000'
}
];
var sorted = dates.sort(function (a, b) {
var reg = /-|:|T|\+/; //The regex on which matches the string should be split (any used delimiter) -> could also be written like /[.:T\+]/
var parsed = [ //an array which holds the date parts for a and b
a.created_time.split(reg), //Split the datestring by the regex to get an array like [Year,Month,Day,Hour,...]
b.created_time.split(reg)
];
var dates = [ //Create an array of dates for a and b
new Date(parsed[0][0], parsed[0][1], parsed[0][2], parsed[0][3], parsed[0][4], parsed[0][5]),//Constructs an date of the above parsed parts (Year,Month...
new Date(parsed[1][0], parsed[1][1], parsed[1][2], parsed[1][3], parsed[1][4], parsed[1][5])
];
return dates[0] - dates[1]; //Returns the difference between the date (if b > a then a - b < 0)
});
这给出了输出:
console.log(sorted);
/*
[{
"created_time": "2013-06-03T01:05:06+0000",
"name": "C"
}, {
"created_time": "2013-06-03T10:05:06+0000",
"name": "B"
}, {
"created_time": "2013-06-05T08:05:06+0000",
"name": "A"
}
]
*/
JSBin上的演示