Skip to content
Advertisement

PrimeVue DataTable Column Sort not Working with Date

I have a DataTable, as listed below:

JavaScript

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:

JavaScript

WHAT I NEED:

JavaScript

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.

Advertisement

Answer

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).

JavaScript

You can retrieve the timestamp of a Date object using either the getTime() method or a unary plus (+) operator.

JavaScript

Ascending sorting

Sorting is then quite easy using the sort() method.

JavaScript

Full example

JavaScript
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement