You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用JavaScript将日/月/年格式的日期数组按最新记录置顶排序

解决日/月/年格式日期数组的排序问题

问题出在new Date()对日/月/年格式的解析逻辑上:当你传入类似"16/03/2023"的字符串时,浏览器会默认按月/日/年规则解析,16作为月份显然无效,最终得到的Date对象可能是错误的甚至是Invalid Date,导致getTime()返回NaN,排序自然失效。

你需要手动解析日/月/年格式的字符串,转换成正确的Date对象后再排序,具体代码如下:

let array = [
  {clmFirstReceivedDt: "16/03/2023"},
  {clmFirstReceivedDt: "17/03/2022"},
  {clmFirstReceivedDt: "13/04/2024"},
  {clmFirstReceivedDt: "06/03/2024"},
  {clmFirstReceivedDt: "06/02/2024"},
  {clmFirstReceivedDt: "12/03/2024"}
];

array.sort((a, b) => {
  // 自定义解析日/月/年格式的函数
  const parseDate = (dateStr) => {
    const [day, month, year] = dateStr.split('/').map(Number);
    // JavaScript中月份是0-based(0代表1月),所以要减1
    return new Date(year, month - 1, day);
  };

  const dateA = parseDate(a.clmFirstReceivedDt).getTime();
  const dateB = parseDate(b.clmFirstReceivedDt).getTime();
  
  return dateB - dateA; // 降序排序,若需升序则改为dateA - dateB
});

console.log(array);

关键说明

  • 用split('/')拆分日期字符串,提取日、月、年的数值
  • 必须将解析到的月份减1,匹配Date构造函数的0-based月份规则
  • 手动解析能避免浏览器对非标准日期格式的解析差异,确保转换准确性

内容的提问来源于stack exchange,提问作者Siva Sai

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.25 16:52:48