如何使用JavaScript的sort()方法按年、月、日降序排列日期?
解决方法
你现有代码仅实现了年份维度的排序,要实现年、月、日全维度降序排序,直接将日期字符串转为Date对象对比时间戳即可,无需手动拆分各维度逐一判断:
修改后的核心逻辑
只需要替换原有的sort排序代码即可:
dates.sort(function (a, b) { return new Date(b.date) - new Date(a.date); });
原理说明
- 你使用的
月份 日, 年格式的字符串可被JS内置Date构造器直接解析 - 两个
Date对象做减法时会自动转换为毫秒级时间戳运算 - 用b的时间戳减去a的时间戳,即可实现日期从新到旧的降序排列
如果你需要更可控的手动对比逻辑(避免不同环境下日期解析差异),也可以使用手动拆分维度的实现:
// 日期解析辅助方法 function getDateParts(dateStr) { const [monthName, dayPart, year] = dateStr.split(' '); const month = new Date(`${monthName} 1`).getMonth(); const day = Number(dayPart.replace(',', '')); return { year: Number(year), month, day }; } dates.sort(function (a, b) { const aInfo = getDateParts(a.date); const bInfo = getDateParts(b.date); // 优先按年降序 if (aInfo.year !== bInfo.year) return bInfo.year - aInfo.year; // 年相同按月降序 if (aInfo.month !== bInfo.month) return bInfo.month - aInfo.month; // 月相同按日降序 return bInfo.day - aInfo.day; });
完整可运行代码
<!DOCTYPE html> <html> <head> <style> .card { padding: 5px 10px; border: 1px solid black; margin: 1em; } </style> </head> <body> <div class="container" id="dateList"></div> <script> const dates = [ { date: "September 4, 2009" }, { date: "July 1, 2009" }, { date: "March 25, 2009" }, { date: "July 8, 2008" }, { date: "May 2, 2008" }, { date: "November 2, 2008" }, { date: "June 9, 2021" }, { date: "August 29, 2007" }, { date: "March 19, 2006" }, { date: "June 22, 2021" }, { date: "May 19, 2021" } ]; // 替换后的排序逻辑 dates.sort(function (a, b) { return new Date(b.date) - new Date(a.date); }); function datesTemplate(d) { return ` <div class="card"> <h3>${d.date}</h3> </div> `; } document.getElementById("dateList").innerHTML = `${dates .map(datesTemplate) .join("")}`; </script> </body> </html>
运行后可看到排序结果完全符合要求:2021年的日期排在最前,同年6月22日排在6月9日之前,2009年的9月排在7月之前等。
内容的提问来源于stack exchange,提问作者Millhorn
相关产品推荐
相关产品推荐

