前端JS数据时间排序

一、sort()方法

var data = [
{
name:‘1’,
time:‘2019-04-26 10:53:19’
},
{
name:‘2’,
time:‘2019-04-26 10:51:19’
},{
name:‘3’,
time:‘2019-04-26 11:04:32’
},{
name:‘4’,
time:‘2019-04-26 11:05:32’
}
]
data.sort(function(a,b){
return a.time < b.time ? 1 : -1
});

二、Date.parse

// 正序
function sortDownDate(a, b) {
return Date.parse(a.received) - Date.parse(b.received);
}
// 反序
function sortUpDate(a, b) {
return Date.parse(b.received) - Date.parse(a.received);
}

var arr=[
{
sender: “elson”,
received: “2017-08-18 13:23:21”,
age: “21”
},
{
sender: “neson”,
received: “2017-03-18 19:23:21”,
age: “22”
},
{
sender: “nelson”,
received: “2015-08-18 13:23:21”,
age: “22”
}
]
//console.log(arr.sort(sortDownDate));//正序
//console.log(arr.sort(sortUpDate));//反序

注意:
parse方法要求短日期可以使用“/”或“-”作为分隔符,但是必须用月/日/年的格式来表示。例如今天是“7/6/2008”或是“7-6-2008”,因为浏览器原因,当使用“7-6-2008”这种格式时,在IE中可以正常解析,但在FireFox中,返回值却总是NaN。

你可能感兴趣的:(JavaScript,javascript,前端,开发语言)