如何在JavaScript中找出日期字符串数组中的最早日期?
问题原因分析
你代码里的核心错误是误用了for...in遍历数组:
for...in遍历数组时,循环变量time拿到的是数组的索引值(字符串形式的"0"、"1"、"2"...),而不是数组里的时间字符串。- 你调用
Date.parse(time)时,其实是在解析这些索引字符串,比如解析"0"会得到对应1970年1月1日的时间戳,完全和你的目标时间无关。 - 这就导致
convertedTimestamps里存的都是索引解析出来的错误时间戳,后续取Math.min或Math.max自然对应不上你的原始日期。
修正方案
有几种简单的修正方式:
方式1:用for...of遍历数组(推荐)
for...of会直接拿到数组里的每一个元素值:
const timestamps = [ '2023-03-15T10:47:38.878Z', '2023-03-15T10:46:51.375Z', '2023-03-15T10:46:39.645Z', '2023-03-15T10:47:19.072Z', '2023-03-15T10:46:20.395Z' ] const convertedTimestamps = []; for (const timeStr of timestamps) { const timeAsDate = Date.parse(timeStr); convertedTimestamps.push(timeAsDate); } const minTimestamp = Math.min(...convertedTimestamps); // 转成日期对象验证 console.log(new Date(minTimestamp)); // 输出最早的日期:2023-03-15T10:46:20.395Z
方式2:用普通for循环遍历索引
如果习惯用索引遍历,记得通过索引取数组元素:
const timestamps = [ '2023-03-15T10:47:38.878Z', '2023-03-15T10:46:51.375Z', '2023-03-15T10:46:39.645Z', '2023-03-15T10:47:19.072Z', '2023-03-15T10:46:20.395Z' ] const convertedTimestamps = []; for (let i = 0; i < timestamps.length; i++) { const timeStr = timestamps[i]; const timeAsDate = Date.parse(timeStr); convertedTimestamps.push(timeAsDate); } const minTimestamp = Math.min(...convertedTimestamps); console.log(new Date(minTimestamp));
方式3:用数组map简化代码
直接用map把字符串转成时间戳,代码更简洁:
const timestamps = [ '2023-03-15T10:47:38.878Z', '2023-03-15T10:46:51.375Z', '2023-03-15T10:46:39.645Z', '2023-03-15T10:47:19.072Z', '2023-03-15T10:46:20.395Z' ] const convertedTimestamps = timestamps.map(str => Date.parse(str)); const minTimestamp = Math.min(...convertedTimestamps); console.log(new Date(minTimestamp));
内容的提问来源于stack exchange,提问作者gggaute
相关产品推荐
相关产品推荐

