Andy
Andy

Reputation: 5395

DataTables and moment.js not sorting by date correctly

I'm trying to use the information on https://datatables.net/blog/2014-12-18 to make DataTables sort a column of dates which are in dd/mm/yyyy format, e.g. 11/10/2018 (representing 11th October 2018).

I have included the following scripts - in this order:

My DataTables initialisation looks like this, as per the information on the URL above:

$(document).ready(function() {
    $.fn.dataTable.moment( 'd/m/Y' );

    $('#coursesTable').DataTable({"searching": false
    });
});

But when I click the date heading in my #coursesTable it gives the following output:

enter image description here

Obviously this is wrong because if the dates are ordered chronologically - most recent first - then 06/09/2017 should appear before 07/08/2017 - but that's not the order they appear in.

When ordering them the other way (oldest first) it gives the same error - i.e. the order is still incorrect:

enter image description here

I can't understand why this is occurring?

Upvotes: 4

Views: 14560

Answers (2)

David Czadilek
David Czadilek

Reputation: 76

Try to change the format to this, according to Moment.js Documentation:

$.fn.dataTable.moment( 'DD/MM/YYYY' );

Here's a working fiddle: http://jsfiddle.net/4f275sa1/

As suggested by @davidkonrad, columnDefs are not needed. And 'DD/MM/YYYY' is the correct format in this case, because the question uses days and months with leading zeroes.

Upvotes: 6

davidkonrad
davidkonrad

Reputation: 85558

The documentation is really vague, but you still need to define the column type:

columnDefs: [{
  target: 0, //index of column
  type: 'datetime-moment'
}]

And as @DavidCzadilek comment, you need use another date format $.fn.dataTable.moment('D/M/YYYY') (the suggested DD/MM/YYYY will not work)

http://jsfiddle.net/xmhn4wpj/

Upvotes: 4

Related Questions