user1034127 user1034127 - 7 months ago 16
Javascript Question

datatable, how to display table sorted by a column in this date format?

I would like to display the table sorted by a column called

createdAt
that has this format :

2015-03-09T14:46:57.678-04:00

Answer

The above date format can be parsed by Date.parse(). So, if you have some columns like this :

<tbody>
    <tr><td>2015-03-09T14:46:54.678-04:00</td></tr>
    <tr><td>2015-03-09T14:46:55.678-04:00</td></tr>
    <tr><td>2015-03-09T14:46:56.678-04:00</td></tr>
    <tr><td>2015-02-09T14:46:57.678-04:00</td></tr>
    <tr><td>2015-02-09T14:46:56.678-04:00</td></tr>
    <tr><td>2015-03-10T02:46:57.678-04:00</td></tr>
    <tr><td>2015-03-11T14:41:57.678-04:00</td></tr>
    <tr><td>2015-03-09T12:46:57.678-04:00</td></tr>
    <tr><td>2015-03-09T01:46:57.678-04:00</td></tr>        
</tbody>

you can make a simple custom sorting plugin and use it for that particular column :

$.fn.dataTableExt.oSort['time-date-sort-pre'] = function(value) {      
    return Date.parse(value);
};
$.fn.dataTableExt.oSort['time-date-sort-asc'] = function(a,b) {      
    return a-b;
};
$.fn.dataTableExt.oSort['time-date-sort-desc'] = function(a,b) {
    return b-a;
};
var table = $('#example').DataTable({
    columnDefs : [
        { type: 'time-date-sort', 
          targets: [0] 
        }
    ]                                     
});

demo -> http://jsfiddle.net/kkrqzvx4/