[英]Javascript - get 1 oldest date from array of dates
I have an array with this format.我有一个这种格式的数组。 I just want to pull the 1 oldest date.
我只想提取 1 个最旧的日期。
This is value in array looks like:这是数组中的值,如下所示:
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']; creationDate = ['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 is my code:这是我的代码:
// this below code is not working as expected
if(creationDate){
var orderedDates = creationDate.sort(function(a,b){
return Date.parse(a) > Date.parse(b);
});
}
Wed Feb 13 21:14:55 GMT 2019格林威治标准时间 2019 年 2 月 13 日星期三 21:14:55
You can use Array.reduce()
and on each iteration compare the dates and take the oldest:您可以使用
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);
You want to return a number, not a Boolean (so use -
not >
):你想返回一个数字,而不是一个布尔值(所以使用
-
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]);
Try:尝试:
if(creationDates){
return creationDates.sort()[0]
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.