Home  >  Q&A  >  body text

Sort PrimeVue DataTable column by date/time

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

<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 populated with data received from the API call, with the field layout listed below:

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

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

How do I sort a column by date and timestamp in ascending or descending order, and right now, sorting the column just rearranges the values ​​based on the first number available (which happens to be the month); I need them to not only correspond to the correct month , also sorted corresponding to time.

Any help is appreciated, thank you.

P粉985686557P粉985686557331 days ago531

reply all(1)I'll reply

  • P粉426906369

    P粉4269063692023-11-23 00:02:03

    What you receive from the API cannot be a Date() object, but may be a string. So if you sort by this column, the rows will be sorted lexicographically, not chronologically.

    To avoid this, you should convert the data from the API to a Date object. Sorting chronologically is very convenient if you convert it to a timestamp:

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

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

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

    reply
    0
  • Cancelreply