08/6
2016
假设现在获得了一些格式化的时间/日期字符串,如何用JavaScript对其排序呢?
理想的办法就是用Date.parse()方法将这些字符串解析为时间,直接比较它们的毫秒数。示例如下:
function sortDate(sortby) { return function(object1, object2) { var value1 = Date.parse(object1); var value2 = Date.parse(object2); if(value1>value2){ return (sortby==="desc")?-1:1; }else if(value1<value2){ return (sortby==="desc")?1:-1; } } } var a=["2017/4/20","2016/6/3","2016/7/1","2016/7/27","2017/8/4","2016/10/13","2016/12/27","2017/1/14","2017/2/3","2017/2/3","2017/2/3","2017/2/3","2017/2/3","2017/2/3","2017/2/3","2017/3/1","2017/3/1","2017/3/1","2017/3/1","2017/3/1","2017/3/1","2017/3/1","2017/3/23","2017/3/31","2017/5/19","2017/5/19","2017/6/2","2017/6/24","2017/6/24","2017/6/24","2017/9/1","2017/9/5","2017/12/12","2018/2/19","2018/9/26","2017/5/19","2017/3/9","2017/7/14","2017/5/19","2017/5/19"]; a.sort(sortDate("desc"));
结果如下:
上例定义了一个sortDate函数,我们在数组的sort方法里将它作为参数。如果不手动设置排序参数为desc,那么这个函数将始终按升序排序。
标准的时间/日期格式如下:
"2017/4/20 16:20:30"
当然,只用一部分,或者改变下连接符,也是可以解析的。
我在这之前还用过一种笨方法,就是按年月日逐个比较数字的大小。比较麻烦,而且也不能处理带时分秒的字符串。姑且留存一下。
function sortAsNumber(sortby) { return function(object1, object2) { var value1 = object1.split("/"); var value2 = object2.split("/"); for (var i = 0; i < value1.length; i++) { if(Number(value1[i])>Number(value2[i])){ return (sortby==="desc")?-1:1; break; }else if(Number(value1[i])<Number(value2[i])){ return (sortby==="desc")?1:-1; break; } } } } var a=["2017/4/20","2016/6/3","2016/7/1","2016/7/27","2017/8/4","2016/10/13","2016/12/27","2017/1/14","2017/2/3","2017/2/3","2017/2/3","2017/2/3","2017/2/3","2017/2/3","2017/2/3","2017/3/1","2017/3/1","2017/3/1","2017/3/1","2017/3/1","2017/3/1","2017/3/1","2017/3/23","2017/3/31","2017/5/19","2017/5/19","2017/6/2","2017/6/24","2017/6/24","2017/6/24","2017/9/1","2017/9/5","2017/12/12","2018/2/19","2018/9/26","2017/5/19","2017/3/9","2017/7/14","2017/5/19","2017/5/19"]; a.sort(sortAsNumber("desc"));