skip to Main Content

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

enter image description here

How can this be fixed?

2

Answers


  1. Chosen as BEST ANSWER

    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'
    

  2. I believe that is happening because you are storing those dates as strings and not as a Date object or a number.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search