Reputation: 407
I'm having issues sorting a datatable with prime react on the Date column.
Here is my code
<Column
field="Date"
header="Date"
sortable={true}
body={(rowData: any) => formatDate(rowData.Date)}
/>
And this is the function that creates a new date instance:
export const formatDate = (date: any) => {
if (!date) return '';
return new Date(date).toLocaleDateString('en-US', {
day: '2-digit',
month: '2-digit',
year: 'numeric',
});
};
When I click the Sorting button it just orders it by the first numbers (days). years are month are being sorted
How can this be fixed?
Upvotes: 0
Views: 218
Reputation: 407
I fixed this mapping the date initially before the conversion
const formatReport = report.map(item => {
return {
...item,
Date: new Date(item.Date)
}
})
This method is called from my DataTable property, report is the useState with data comming from the DB.
<DataTable
value={formatReport}//This calls the function to map and make the date(data object)
style={{ textAlign: 'center' }}
sortField='Date'
sortOrder={1}
editMode='cell'
scrollable
scrollHeight='45vh'
Upvotes: 1
Reputation: 140
I believe that is happening because you are storing those dates as strings and not as a Date object or a number.
Upvotes: 2