2017-10-18 57 views
1

我想约会我的列进行排序:如何按日期排序我的DataTables行?

var table = $('#table').DataTable({ 
    "order": [[0, "desc"]], 
}); 

但这里是我的结果:

29.06.17 
27.06.17 
26.06.17 
22.08.17 
18.10.17 
15.09.17 

什么我希望是这样的:

18.10.17 
15.09.17 
22.08.17  
29.06.17 
27.06.17 
26.06.17 

六月,然后八月,然后9月,然后10月......

我测试了也:

"columnDefs": [ 
    { "type": "date-dd.mm.yy", targets: 0 } 
], 

但是这并没有改变任何东西。

+0

我猜你有dateobjects工作,使其sortabl即请参阅:https://www.w3schools.com/jsref/jsref_obj_date.asp –

+0

它是什么语言? – 1010

回答

1

dataTables date type uses Data.parse()它只支持一组有限的日期格式。欧式风格dd.mm.yy不可解析,因此日期是按alpha排序的。

可以对付data attributes,即增加一个data-sort="10/18/17"每一列,但我认为这是更容易地创建一个小插件,返回有效日期:

$.extend($.fn.dataTableExt.oSort, { 
    "jarla-date-pre": function(a) { 
    a = a.split('.'); 
    return new Date(a[1]+'/'+a[0]+'/'+a[2]) 
    } 
}); 

使用方法如下:

columnDefs: [ 
    { type: 'jarla-date', targets: 0 } 
] 

演示 - >http://jsfiddle.net/vad94dcs/

+0

这工作真棒! – Jarla

0

您需要使用render函数,该函数允许您格式化显示日期并使用原始日期值进行排序。

以下代码使用moment.js javascript库格式化日期。

{ 
    data: 'DateField', 
    render: function (data, type, row) { 
    // If display or filter data is requested, format the date 
    if (type === 'display' || type === 'filter') { 

        return (moment(data).format("ddd DD/MM/YYYY (HH:mm)")); 
       } 
    // Otherwise the data type requested (`type`) is type detection or 
    // sorting data, for which we want to use the raw date value, so just return 
    // that, unaltered 
       return data; 
      } 
     }, 

datatables forum, here链接到源。