数据表中日期时间列的排序问题

问题描述 投票:0回答:2

我的表中有一个包含日期时间对象的列。我正在使用数据表插件。 在尝试对特定列进行排序时,它会被错误排序。比如,以下日期

Aug. 20, 2018, 11:16 a.m.  
Aug. 2, 2018, 12:25 p.m. 
Aug. 4, 2018, 3:03 p.m. 

我得到的排序结果为

Aug. 2, 2018, 12:25 p.m.  
Aug. 20, 2018, 11:16 a.m.  
Aug. 4, 2018, 3:03 p.m.  

应该采取什么措施来纠正这个问题?

datetime datatables
2个回答
0
投票

jquery官方文档中所述,只能对指定格式的数据进行排序。

要对日期或时间进行排序,您可以添加以下行来对日期或时间进行排序:

$('#example').dataTable( {
     columnDefs: [
       { type: 'date-uk', targets: 0 }
     ]
  } );

0 是列的索引。您可以根据您的列索引进行修改。 如果您收到相同格式的数据,您可以将类型

date-uk
更改为文档中提到的任何其他类型。


0
投票

请务必阅读主要问题的所有评论,以便您更好地理解以下解决方案。

以下是对我有用的正确组合。

在您的 HTML 上

<td data-order="{{ starts_at|date:'U' }}">{{ starts_at }}</td>

在你的 JS 文件中
  • 添加日期时间作为数据表的类型
$.fn.dataTable.ext.type.order['datetime-pre'] = function (data) {
    return new Date(data).getTime();
}; 
  • 然后在您的 columnsDefs 上使用它
"order": [[1, 'asc']],
"columnDefs": [
   {"targets": [1], "orderable": true, "type": "datetime-pre"},
]
© www.soinside.com 2019 - 2024. All rights reserved.