如何按日期时间格式对文件名数组进行排序?
按文件名中的日期时间排序数组
要让fetchArray排序后和expectedArray一致,核心是正确解析文件名里的DD-MM-YYYY_HH-mm-ss格式日期,再按时间先后升序排列(旧日期在前)。直接字符串排序会因为日期格式的问题出错,得先把日期转成可比较的Date对象。
具体实现步骤
- 提取并转换日期:写一个辅助函数,从文件路径中提取日期时间字符串,转换成JavaScript能识别的标准日期格式,生成
Date对象。 - 数组排序:使用数组的
sort方法,比较两个元素对应的Date对象的时间戳,实现升序排序。
完整代码
const fetchArray = [ "root/home/desktop/usr/public/images/09-01-2023_07-17-00.jpg", "root/home/desktop/usr/public/images/09-01-2023_07-17-29.jpg", "root/home/desktop/usr/public/images/30-11-2022_10-39-29.jpg", ]; // 从文件路径中提取日期并转为时间戳 function getFileTimestamp(filePath) { // 取出文件名部分 const fileName = filePath.split('/').pop(); // 去掉.jpg后缀,拿到纯日期时间字符串 const dateTimeStr = fileName.slice(0, -4); // 拆分日期和时间段 const [datePart, timePart] = dateTimeStr.split('_'); // 拆分日、月、年和时、分、秒 const [day, month, year] = datePart.split('-'); const [hour, minute, second] = timePart.split('-'); // 重组为ISO格式,生成Date对象后取时间戳 return new Date(`${year}-${month}-${day}T${hour}:${minute}:${second}`).getTime(); } // 按时间戳升序排序(旧日期在前) const sortedArray = fetchArray.sort((a, b) => { return getFileTimestamp(a) - getFileTimestamp(b); }); console.log(sortedArray); // 输出结果与expectedArray完全一致
代码说明
getFileTimestamp函数:负责从路径中提取日期信息,将DD-MM-YYYY_HH-mm-ss转换为YYYY-MM-DDTHH:mm:ss的标准格式,生成Date对象后获取时间戳(数字类型,方便直接比较)。sort方法中的比较函数:通过时间戳的差值判断顺序,差值为负时,a的日期更早,排在前面;差值为正时,b的日期更早,排在前面,最终实现从旧到新的排序。
内容的提问来源于stack exchange,提问作者Yong Wei Sin
相关产品推荐
相关产品推荐

