Why sorting is not working on date columns?

Why sorting is not working on date columns?

MoizMoiz Posts: 32Questions: 5Answers: 1

Hi,
http://live.datatables.net/kilayuce/8/edit , as you can see in this test case sorting is not working on joining and leaving columns.
The format I'm using for dates is something like this 'DD/MM/YYYY'. Plus, I'm using the moment.js and following this link for sorting dates -> https://datatables.net/blog/2014-12-18#The-need-for-a-flexible-solution . Maybe, I'm doing something wrong or missing something important. As far as this comment is considered,

I'm using 2.18.1 version of moment.js. Please guide

This question has an accepted answers - jump to answer

Answers

  • MoizMoiz Posts: 32Questions: 5Answers: 1

    Brother, @colin Any guidance?

  • kthorngrenkthorngren Posts: 7,010Questions: 22Answers: 1,529
    Answer ✓

    There are a few problems with your code :smile:

    The first problem is this error in the browser's console:

    Uncaught TypeError: $.fn.dataTable.moment is not a function

    The datetime-moment.js requires moment.js so moment.js needs to be loaded first, like this:

        <script src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.js"></script>
        <script src="//cdn.datatables.net/plug-ins/1.10.20/sorting/datetime-moment.js"></script>
    

    The second problem is the format ($.fn.dataTable.moment( 'DD/MM/YYYY' );) needs to be defined before initializing Datatables.

    Third problem is you are loading datetime-moment.js and you copied the code from datetime-moment.js into the Javascript.

    Forth problem is that the columns have type: 'date' defined for the search plugin function to work. In order for the datetime-moment plugin to work it needs to set the column type using this code:

    $.fn.dataTable.ext.type.detect.unshift( function ( d ) {
        return moment( d, format, locale, true ).isValid() ?
            'moment-'+format :
            null;
    } );
    

    Now you need to remove the type: 'date' option and use the type assigned by the plugin in your search plugin. Datatables won't set the type using type but using sType. The if (col.type == "moment-DD/MM/YYYY") needs to change to if (col.sType == "moment-DD/MM/YYYY"). With this solution you won't be able to use the type to differentiate the columns in the plugin but will need to use the column number.

    Here is the updated example:
    http://live.datatables.net/kilayuce/10/edit

    Kevin

  • MoizMoiz Posts: 32Questions: 5Answers: 1

    Well, that's a lot of errors. :D Thanks brother, Kevin!

Sign In or Register to comment.