I am having an array
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"}
];
I am having the date in the day, month, year format when i try
array.sort((a, b) => {
const dateA = new Date(a.clmFirstReceivedDt).getTime();
const dateB = new Date(b.clmFirstReceivedDt).getTime();
return dateB - dateA;
});
when the format is month, day, year its working fine but when the date format is changed then order is not getting sorted properly
4
Answers
How the
Date
constructor parses such strings should not be relied on. Instead construct strings you can order lexically, or their numeric equivalent. Here I rearrange the numeric parts to create one big number (yyyymmdd) and then it works:There you go, if you want to sort the dates which are in the dd/mm/yy format ->
hope this helps 🙂
To ensure proper sorting regardless of the date format, you should parse the date string manually before creating the Date object. You can achieve this by splitting the date string and creating a new Date object with the year, month, and day in the correct order.
Point to noted: Javascript only accept dates format YYYY-MM-DD or MM-DD-DD. You must specify format first which format you are using, if you are using other than above two you should update your format first in your logic than sort the array. Like this