PrimeVue DataTable Column Sort by Date/Time

Viewed 109

I have a PrimeVue DataTable (https://primefaces.org/primevue/datatable) that is arranged as such:

<DataTable
  :rows = "5"
  :value = "apiItems"
>
  <Column
    v-for="data in columns"
    :field="data.field"
    :header="data.header"
    :key="data.field"
    :sortable="true"
    />
</DataTable>

Where the table is being populated by data received from an API call, and the field layout is as listed:

const columns = [
  { field: 'initialDate', header: 'Initial Date'},
  { field: 'finishDate', header: 'Finish Date'}
];

The data being retrieved from the API is in the form of a JS Date() component that is displayed as such: "08/01/2022 08:33:32" for both initialDate and finishDate

How can I the columns via ascending or descending by both the date AND time stamps, whereas now, sorting the columns just rearranges the values based on the first digits available, which happen to be the month; I need them to sort corresponding to not only the correct month, but the time as well.

Any help is appreciated, thanks.

1 Answers

What you are receiving from the API cannot be a Date() object, but is probably a string. And so, if you sort by this column, the rows are sorted lexicographically, but not chronologically.

To avoid that, you should convert the data coming from the API into Date objects. If you convert that to a timestamp, that's very convenient to sort by chronologically:

for (item of apiItems) {
  item.initialDateObj = new Date(item.initialDate)
  item.initialDateTimestamp = item.intialDateTimeObj.getTime()
}

You can then specify that as the field to sort a column by:

const columns = [
  { field: 'initialDate', sortField: 'initialDateTimestamp', header: 'Initial Date'},
  { field: 'finishDate', sortField: 'finishDateTimestamp', header: 'Finish Date'}
];
Related