peace_love
peace_love

Reputation: 6461

How can I sort my DataTables row by date?

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.

Upvotes: 1

Views: 409

Answers (2)

davidkonrad
davidkonrad

Reputation: 85528

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/

Upvotes: 2

melkisadek
melkisadek

Reputation: 1053

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.

Upvotes: 0

Related Questions