如何在Javascript中对日期和时间进行排序(最新的在前)?

问题描述 投票:0回答:1

我知道有一些与此类似的问题,但还没有找到像我这样的数据结构。

我的对象数组

const dateAndTime = [
  {
    "createdAt": "20/02/2024, 16:13:51"
  },
  {
    "createdAt": "20/02/2024, 16:15:23"
  },
  {
    "createdAt": "18/02/2024, 14:27:31"
  },
  {
    "createdAt": "18/02/2024, 15:41:06"
  },
  {
    "createdAt": "21/03/2024, 22:09:35"
  },
  {
    "createdAt": "07/03/2024, 17:24:19"
  },
];

这是我构建的排序函数(最新的优先)

 dateAndTime.sort((a, b) => {
  const dateA = new Date(a.createdAt);
  const dateB = new Date(b.createdAt);
  return dateB.getTime() - dateA.getTime();
});

console.log(dateAndTime);

输出

[
  {
    "createdAt": "20/02/2024, 16:13:51"
  },
  {
    "createdAt": "20/02/2024, 16:15:23"
  },
  {
    "createdAt": "18/02/2024, 14:27:31"
  },
  {
    "createdAt": "18/02/2024, 15:41:06"
  },
  {
    "createdAt": "21/03/2024, 22:09:35"
  },
  {
    "createdAt": "07/03/2024, 17:24:19"
  },
]

预期产出

[
  {
    "createdAt": "21/03/2024, 22:09:35"
  },
  {
    "createdAt": "07/03/2024, 17:24:19"
  },
  {
    "createdAt": "20/02/2024, 16:15:23"
  },
  {
    "createdAt": "20/02/2024, 16:13:51"
  },
  {
    "createdAt": "18/02/2024, 15:41:06"
  },
  {
    "createdAt": "18/02/2024, 14:27:31"
  },
]

如您所见,输出几乎相同,它似乎没有将最新的排在最前面。预期输出首先是最新的,因此 2024 年 3 月 21 日 10:09:35 PM 应该是数组中的第一个对象,然后它从那里开始变旧。

我哪里出错了?

提前非常感谢!

javascript sorting data-structures
1个回答
0
投票

解析日期和时间并将其转换为 JavaScript Date 对象

const parsedDates = dateAndTime.map(item => {
  const [date, time] = item.createdAt.split(', ');
  const [day, month, year] = date.split('/');
  const [hours, minutes, seconds] = time.split(':');
  return new Date(year, month - 1, day, hours, minutes, seconds);
});

对 Date 对象数组进行排序

parsedDates.sort((a, b) => a - b);

将排序后的 Date 对象映射回原始格式

const sortedDateAndTime = parsedDates.map(date => {
  const day = String(date.getDate()).padStart(2, '0');
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const year = date.getFullYear();
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  const seconds = String(date.getSeconds()).padStart(2, '0');
  return { "createdAt": `${day}/${month}/${year}, ${hours}:${minutes}:${seconds}` };
});

console.log(sortedDateAndTime);
© www.soinside.com 2019 - 2024. All rights reserved.