我有一个具有这种格式的数组。我只想拉最早的日期。
这是数组中的值,看起来像:
creationDate = ['Wed Feb 13 21:14:55 GMT 2019','Wed Feb 13 21:19:42 GMT 2019','Wed Feb 13 21:28:29 GMT 2019','Wed Feb 13 21 :31:04 GMT 2019'];
这是我的代码:
// this below code is not working as expected
if(creationDate){
var orderedDates = creationDate.sort(function(a,b){
return Date.parse(a) > Date.parse(b);
});
}
2019年2月13日星期三21:14:55 GMT
答案 0 :(得分:1)
尝试:
if(creationDates){
return creationDates.sort()[0]
}
答案 1 :(得分:1)
您可以使用Array.reduce()
,并在每次迭代中比较日期并采用最早的日期:
const creationDate = ['Wed Feb 13 21:14:55 GMT 2019','Wed Feb 13 21:19:42 GMT 2019','Wed Feb 13 21:28:29 GMT 2019','Wed Feb 13 21:31:04 GMT 2019'];
const oldest = creationDate.reduce((c, n) =>
Date.parse(n) < Date.parse(c) ? n : c
);
console.log(oldest);
答案 2 :(得分:1)
您要返回数字,而不是布尔值(因此,请使用-
而不是>
):
var creationDate = ['Wed Feb 13 21:14:55 GMT 2019', 'Wed Feb 13 21:19:42 GMT 2019', 'Wed Feb 13 21:28:29 GMT 2019', 'Wed Feb 13 21:31:04 GMT 2019'];
var orderedDates = creationDate.sort(function(a, b) {
return Date.parse(a) > Date.parse(b);
});
console.log(orderedDates[0]);