简体   繁体   English

PrimeVue DataTable 列排序不适用于日期

[英]PrimeVue DataTable Column Sort not Working with Date

I have a DataTable, as listed below:我有一个 DataTable,如下所示:

<DataTable
  :rows = "5"
  :value = "apiItems"
>
  <Column
    :field="initialDate"
    :header="Initial Date"
    :sortable="true"
    />
    
    <Column
    :field="finishDate"
    :header="Finish Date"
    :sortable="true"
    />
</DataTable>

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" initialDate 和 finishDate 都是从 API 调用中提取的数据字段,看起来像这样:“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:它能做什么:

Ascending:
"08/22/2021 11:43:12"
"07/01/2022 12:01:09"

WHAT I NEED:我需要的:

Ascending:
"07/01/2022 12:01:09"
"08/22/2021 11:43:12"

WHAT I'VE TRIED: Attempted to turn the already present date into a JS Data object as such: new Date(initialDate).toLocaleString().我尝试过的:尝试将已经存在的日期转换为 JS 数据 object,例如:new Date(initialDate).toLocaleString()。 Doesn't sort properly still.仍然不能正确排序。

Thanks for the Assistance.感谢您的协助。

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) .要对日期进行排序,您必须能够比较它们,最好的方法是将它们转换为时间戳(自 1970 年 1 月 1 日 00:00:00 UTC 以来经过的毫秒数)

const date1 = new Date('08/22/2021 11:43:12')
const date2 = new Date('07/01/2022 12:01:09')

You can retrieve the timestamp of a Date object using either the getTime() method or a unary plus (+) operator .您可以使用getTime()方法或一元加号 (+) 运算符检索日期 object的时间戳。

console.log(date1.getTime()) // 1629603792000
console.log(+date2) // 1656648069000

Ascending sorting升序排序

Sorting is then quite easy using the sort() method.使用sort()方法进行排序非常容易。

console.log([date1, date2].sort((a,b) => +b - +a))

Full example完整示例

 const date1 = new Date('08/22/2021 11:43:12') const date2 = new Date('07/01/2022 12:01:09') console.log([date1, date2].sort((a,b) => +b - +a))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM