How to sort by Date with DataTables jquery plugin?

chobo2 picture chobo2 · May 19, 2010 · Viewed 99.8k times · Source

I am using the datatables jquery plugin and want to sorty by dates.

I know they got a plugin but I can't find where to actually download it from

http://datatables.net/plug-ins/sorting

I believe I need this file: dataTables.numericComma.js yet I can't find it anywhere and when I download datatables it does not seem to be in the zip file.

I am also not sure if I need to make my own custom date sorter to pass into this plugin.

I am trying to sort this format MM/DD/YYYY HH:MM TT(AM |PM)

Thanks

Edit

How can I change this to sort by MM/DD/YYYY HH:MM TT(AM |PM) and change it to U.S date?

jQuery.fn.dataTableExt.oSort['uk_date-asc']  = function(a,b) {
    var ukDatea = a.split('/');
    var ukDateb = b.split('/');

    var x = (ukDatea[2] + ukDatea[1] + ukDatea[0]) * 1;
    var y = (ukDateb[2] + ukDateb[1] + ukDateb[0]) * 1;

    return ((x < y) ? -1 : ((x > y) ?  1 : 0));
};

jQuery.fn.dataTableExt.oSort['uk_date-desc'] = function(a,b) {
    var ukDatea = a.split('/');
    var ukDateb = b.split('/');

    var x = (ukDatea[2] + ukDatea[1] + ukDatea[0]) * 1;
    var y = (ukDateb[2] + ukDateb[1] + ukDateb[0]) * 1;

    return ((x < y) ? 1 : ((x > y) ?  -1 : 0));
};

Answer

Anulal S picture Anulal S · Aug 18, 2014

Date Sort - with a hidden element

Convert the date to the format YYYYMMDD and prepend to the actual value (MM/DD/YYYY) in the <td>, wrap it in an element, set style display:none; to the elements. Now the date sort will work as a normal sort. The same can be applied to date-time sort.

HTML

<table id="data-table">
   <tr>
     <td><span>YYYYMMDD</span>MM/DD/YYYY</td>
   </tr>
</table>

CSS

#data-table span {
    display:none; 
}