How to fix sorting for Date format dd-mm-yyyy?

How to fix sorting for Date format dd-mm-yyyy?

mastersusemastersuse Posts: 61Questions: 28Answers: 0

I have datatables that contain of multiple column of date. But all the column date is not work perfectly for sorting asc and desc.

For instance:

This is my Datatable for image above, just to inform that I have a function to display date only with dd-mm-yyyy format.

$('#projectListTable').DataTable({
    columns: [
        { data : "planned_date",
            render: function(data){
                if (data == null){
                    return data;
                }
                else {
                    new_data = data.split("T");
                    new_data[0] = displayDate(new_data[0]);
                    return new_data[0];
                }
            }
        },
        { data : "planned_finish",
            render: function(data){
                if (data == null){
                    return data;
                }
                else {
                    new_data = data.split("T");
                    new_data[0] = displayDate(new_data[0]);
                    return new_data[0];
                }
            }
        }
    ],
});

Answers

  • tangerinetangerine Posts: 3,354Questions: 37Answers: 394

    There are many posts in here about date sorting. For example:
    https://datatables.net/forums/discussion/53126

  • mastersusemastersuse Posts: 61Questions: 28Answers: 0

    yes I read it, but do not know which is better and suit with my problem.

  • mastersusemastersuse Posts: 61Questions: 28Answers: 0

    I found this solution, but how to combine with mine? Please guide by answering with proper code. I am blurring.

    Where is type: 'extract-date come from? and what does mean by targets: [0]?

    https://datatables.net/forums/discussion/41076/how-to-sort-table-by-dd-mm-yyyy

    $(document).ready(function() {
       jQuery.extend(jQuery.fn.dataTableExt.oSort, {
        "extract-date-pre": function(value) {
            var date = $(value, 'span')[0].innerHTML;
            date = date.split('/');
            return Date.parse(date[1] + '/' + date[0] + '/' + date[2])
        },
        "extract-date-asc": function(a, b) {
            return ((a < b) ? -1 : ((a > b) ? 1 : 0));
        },
        "extract-date-desc": function(a, b) {
            return ((a < b) ? 1 : ((a > b) ? -1 : 0));
        }
    });
    $('#leadtable').dataTable({
        language: {
            url: '//cdn.datatables.net/plug-ins/1.10.12/i18n/Hebrew.json'
        },
        columnDefs: [{
                type: 'extract-date',
                targets: [0]
            }
     
        ]
    });
    
  • colincolin Posts: 15,202Questions: 1Answers: 2,592

    extract-date is the type, you see it declared at the top, then used on line 20. And see columnDefs.targets - it's the column number.

    Colin

This discussion has been closed.