How can I sort my DataTables row by date?

左心房为你撑大大i 提交于 2021-01-28 07:59:51

问题


I want to sort my column by date:

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

But here is my result:

29.06.17
27.06.17
26.06.17
22.08.17
18.10.17
15.09.17

What I would expect is this:

18.10.17
15.09.17
22.08.17    
29.06.17
27.06.17
26.06.17

June, then August, then September and then October....

I tested also:

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

But this didn't change anything.


回答1:


dataTables date type uses Data.parse() which only supports a limited set of date formats. European style dd.mm.yy is not parseable thus the dates is alpha sorted.

You can deal with data attributes, i.e adding a data-sort="10/18/17" to each column, but I think it is easier to create a small plugin that return valid dates :

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

Use it like this :

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

demo -> http://jsfiddle.net/vad94dcs/




回答2:


You need to use the render function which allows you to both format the date for display and use the raw date value for sorting.

The following code uses the moment.js javascript library to format the date.

{
     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;
            }
        },

Link to source at the datatables forum, here.



来源:https://stackoverflow.com/questions/46808260/how-can-i-sort-my-datatables-row-by-date

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!