jquerydatatablesdate-sorting

Datatable date sorting dd/mm/yyyy issue


I am using a Jquery plugin called datatables

Its fantastic, however I cannot get the dates to sort correctly according to the dd/mm/yyyy format.

I have looked at their support formats but none of these fixes seem to work.

Can anybody here help me please?


Solution

  • Update 2020: HTML Solution

    Since HTML 5 is so much developed and almost all major browser supporting it. So now a much cleaner approach is to use HTML5 data attributes (maxx777 provided a PHP solution I am using the simple HTML). For non-numeric data as in our scenario, we can use data-sort or data-order attribute and assign a sortable value to it.

    HTML

    <td data-sort='YYYYMMDD'>DD/MM/YYYY</td>
    

    Here is working HTML solution

    jQuery Solution

    Here is working jQuery solution.

    jQuery.extend( jQuery.fn.dataTableExt.oSort, {
    "date-uk-pre": function ( a ) {
        var ukDatea = a.split('/');
        return (ukDatea[2] + ukDatea[1] + ukDatea[0]) * 1;
    },
    
    "date-uk-asc": function ( a, b ) {
        return ((a < b) ? -1 : ((a > b) ? 1 : 0));
    },
    
    "date-uk-desc": function ( a, b ) {
        return ((a < b) ? 1 : ((a > b) ? -1 : 0));
    }
    } );
     
    

    Add the above code to script and set the specific column with Date values with { "sType": "date-uk" } and others as null, see below:

    $(document).ready(function() {
        $('#example').dataTable( {
            "aoColumns": [
                null,
                null,
                null,
                null,
                { "sType": "date-uk" },
                null
            ]
        });
        });