I have a DataTable, as listed below:
<DataTable
:rows = "5"
:value = "apiItems"
>
<Column
:field="initialDate"
:header="Initial Date"
:sortable="true"
/>
<Column
:field="finishDate"
:header="Finish Date"
:sortable="true"
/>
</DataTable>
initialDate and finishDate are both data fields that are pulled from an API call, and will look something like this: "08/21/2022 11:43:12"
When I attempt to sort these columns, they do not sort by the actual date (which is what I need), but just the first number in the string (which is the month)
WHAT IT DOES:
Ascending:
"08/22/2021 11:43:12"
"07/01/2022 12:01:09"
WHAT I NEED:
Ascending:
"07/01/2022 12:01:09"
"08/22/2021 11:43:12"
WHAT I'VE TRIED: Attempted to turn the already present date into a JS Data object as such: new Date(initialDate).toLocaleString(). Doesn't sort properly still.
Thanks for the Assistance.
CodePudding user response:
To sort dates, you must be able to compare them, and the best way to do it is to convert them into timestamps (number of milliseconds elapsed since January 1, 1970, 00:00:00 UTC).
const date1 = new Date('08/22/2021 11:43:12')
const date2 = new Date('07/01/2022 12:01:09')
You can retrieve the timestamp of a Date object using either the getTime() method or a unary plus ( ) operator.
console.log(date1.getTime()) // 1629603792000
console.log( date2) // 1656648069000
Ascending sorting
Sorting is then quite easy using the sort() method.
console.log([date1, date2].sort((a,b) => b - a))
Full example
const date1 = new Date('08/22/2021 11:43:12')
const date2 = new Date('07/01/2022 12:01:09')
console.log([date1, date2].sort((a,b) => b - a))