1

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.

2
  • I guess you have to work with dateobjects to make it sortable. See: w3schools.com/jsref/jsref_obj_date.asp Commented Oct 18, 2017 at 10:42
  • What language is it? Commented Oct 18, 2017 at 11:01

2 Answers 2

2

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/

Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.