如何从字符串日期数组中获取最大日期字符串?

时间:2018-12-29 18:48:07

标签: javascript

从如下所示的字符串数组中获取最大日期的最优雅的方法是什么?

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)

但是,这给我留下了一个时间戳,我需要将其转换回精确原始格式(而且我不知道该怎么做)。

2 个答案:

答案 0 :(得分:1)

您可以像字符串一样比较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);

答案 1 :(得分:0)

这是toISOStringDate上提供的格式。因此,您将时间戳记值输入到new Date中,并在结果上使用toISOString

console.log(new Date(max_date).toISOString());

示例:

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());

请注意,您得到"2018-12-29T15:23:31.548Z"而不是"2018-12-29T15:23:31.548761Z",因为您已将字符串解析为JavaScript日期,并且JavaScript日期仅保留毫秒,而不是微秒。