[英]How to get a string of max date from an array of string dates?
What would be the most elegant way to get max date from an array of strings like below?从如下所示的字符串数组中获取最大日期的最优雅方法是什么?
var dates = ["2018-12-29T15:23:20.486695Z", "2018-12-29T15:23:21.613216Z", "2018-12-29T15:23:22.695710Z", "2018-12-29T15:23:24.013567Z", "2018-12-29T15:23:25.097649Z", "2018-12-29T15:23:26.692125Z", "2018-12-29T15:23:27.918561Z", "2018-12-29T15:23:29.217879Z", "2018-12-29T15:23:30.468284Z", "2018-12-29T15:23:31.548761Z"]
I have tried:我试过了:
var timestamps = dates.map(date => Date.parse(date));
var max_date = Math.max.apply(Math, timestamps)
But this leaves me with a timestamp that I would need to convert back to the exact original format (and I don't know how to do that).但这给我留下了一个时间戳,我需要将其转换回确切的原始格式(我不知道该怎么做)。
You could compare the ISO 8601 date like strings and take the greater value.您可以像字符串一样比较ISO 8601日期并取更大的值。
var dates = ["2018-12-29T15:23:20.486695Z", "2018-12-29T15:23:21.613216Z", "2018-12-29T15:23:22.695710Z", "2018-12-29T15:23:24.013567Z", "2018-12-29T15:23:25.097649Z", "2018-12-29T15:23:26.692125Z", "2018-12-29T15:23:27.918561Z", "2018-12-29T15:23:29.217879Z", "2018-12-29T15:23:30.468284Z", "2018-12-29T15:23:31.548761Z"], latest = dates.reduce((a, b) => a > b ? a : b); console.log(latest);
That's the format provided by toISOString
on Date
.这是
toISOString
在Date
上提供的格式。 So you take your timestamp value, feed it into new Date
, and use toISOString
on the result:因此,您将时间戳值输入到
new Date
,然后对结果使用toISOString
:
console.log(new Date(max_date).toISOString());
Example:例子:
var dates = [ "2018-12-29T15:23:20.486695Z", "2018-12-29T15:23:21.613216Z", "2018-12-29T15:23:22.695710Z", "2018-12-29T15:23:24.013567Z", "2018-12-29T15:23:25.097649Z", "2018-12-29T15:23:26.692125Z", "2018-12-29T15:23:27.918561Z", "2018-12-29T15:23:29.217879Z", "2018-12-29T15:23:30.468284Z", "2018-12-29T15:23:31.548761Z" ]; var timestamps = dates.map(date => Date.parse(date)); var max_date = Math.max.apply(Math, timestamps) console.log(new Date(max_date).toISOString());
Note that you get "2018-12-29T15:23:31.548Z"
rather than "2018-12-29T15:23:31.548761Z"
because you've parsed the strings to JavaScript dates, and JavaScript dates only hold milliseconds, not microseconds.请注意,您得到的是
"2018-12-29T15:23:31.548Z"
而不是"2018-12-29T15:23:31.548761Z"
因为您已将字符串解析为 JavaScript 日期,而 JavaScript 日期仅保留毫秒,而不是微秒.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.