orb*_*xus 1 javascript arrays date
我有一个具有这种格式的数组。我只想拉出 1 个最旧的日期。
这是数组中的值,如下所示:
createDate = ['2019 年 2 月 13 日星期三 21:14:55 GMT','2019 年 2 月 13 日星期三 21:19:42 GMT','2019 年 2 月 13 日星期三 21:28:29 GMT','2 月 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);
});
}
Run Code Online (Sandbox Code Playgroud)
2019 年 2 月 13 日星期三 21:14:55 GMT
您可以使用Array.reduce()and 在每次迭代中比较日期并取最旧的:
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);Run Code Online (Sandbox Code Playgroud)
您想要返回一个数字,而不是布尔值(因此使用-not >):
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', 'Wed Feb 13 21:33:04 GMT 2019'];
var orderedDates = creationDate.sort(function(a, b) {
return Date.parse(a) - Date.parse(b);
});
console.log(orderedDates[0]);Run Code Online (Sandbox Code Playgroud)