我正在使用 jquery 数据表插件列出我的 java spring MVC Web 应用程序中的数据。表中的字段之一包含带时间戳的日期。在这方面,我一直在尝试对数据元素进行排序。当我尝试对包含带有时间戳的日期的字段中的元素进行排序时,排序不起作用。
我使用以下 jquery 进行数据表初始化
$('.swcm-dt-basic').dataTable( {
"responsive": true,
"order": \[\],
"language": {
"paginate": {
"previous": '<i class="swcm-psi-arrow-left"></i>',
"next": '<i class="swcm-psi-arrow-right"></i>'
}
}
} );
下图显示了这个问题
最佳答案
解决方案 1
对包含可排序时间戳的 td
元素使用 data-order
属性。例如:
<td data-order="2016-12-02 21:28:41">12/02/2016 21:28:41</td>
参见this example用于代码和演示。
解决方案2
使用sorting plugins像datetime-moment对于任何日期格式或 date-euro如果您的日期采用 DD/MM/YYYY HH:MM:SS
格式。
如果您的日期采用 MM/DD/YYYY HH:MM:SS
格式,则可以使用以下代码:
jQuery.extend( jQuery.fn.dataTableExt.oSort, {
"date-us-pre": function ( a ) {
var x;
if ( $.trim(a) !== '' ) {
var frDatea = $.trim(a).split(' ');
var frTimea = (undefined != frDatea[1]) ? frDatea[1].split(':') : [00,00,00];
var frDatea2 = frDatea[0].split('/');
x = (frDatea2[2] + frDatea2[0] + frDatea2[1] + frTimea[0] + frTimea[1] + frTimea[2]) * 1;
}
else {
x = Infinity;
}
return x;
},
"date-us-asc": function ( a, b ) {
return a - b;
},
"date-us-desc": function ( a, b ) {
return b - a;
}
} );
$(document).ready(function(){
$('#example').dataTable( {
columnDefs: [
{ type: 'date-us', targets: 0 }
]
} );
}
关于javascript - JQuery 数据表中的日期与时间戳排序问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42563449/