4

In my project I want to sort date which is in dd-mm-yyyy format. I tried like this below

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));
    }
});

But this is not working. Here only date and month is getting sorted not also on the basis of year. I took reference from here Datatable date sorting dd/mm/yyyy issue

Community
  • 1
  • 1
Anju
  • 502
  • 1
  • 6
  • 20

3 Answers3

12

I know this is an old question, but in case you've just come here from Google, there is a built in solution now.

Just add an HTML5 attribute to the element:

<td data-th="Lastrun" data-order="[unixTimestamp]">
    [myWeirdDateFormat]
</td>

https://datatables.net/examples/advanced_init/html5-data-attributes.html

markBlack
  • 198
  • 3
  • 12
1

Well it works for me out of the box but I have less complicated date and times so probably its best if you use this http://datatables.net/plug-ins/sorting/

Rohit Hazra
  • 657
  • 9
  • 27
0

With hidden dynamic span elements

In my case, data was being retrieved dynamically from the server, so I found out this solution

           var data = aResponce.noOfShipmentsTableData; //dynamic data from server
           for (var i = 0; i < data.length; i++) {
            var array = [];
            var pickUpDate = data[i]["pickUpDate"]; //date to sort
            var span = pickUpDate.split("/");
            if (span[1].length == 1) 
                span[1] =  "0" + span[1];
            if (span[0].length == 1) 
                span[0] =  "0" + span[0];

            span = "<span class='hideSpan'>"+span[2]+span[1]+span[0]+"</span>";
            var PickUpDateTd = "<td>"+span+pickUpDate+"</td>";
            array.push(PickUpDateTd); //push as many values you want in one row of datatable

            totalCtsBookedTbl.api().row.add(array); //totalCtsBookedTbl is reference variable to my datatable
        }
        totalCtsBookedTbl.api().draw();

.hideSpan {
  display: none;
}
Muhammad Awais
  • 1,608
  • 1
  • 21
  • 21