Tuesday, January 4, 2011

DataTables Date Sorting

If you're using DataTables found at http://www.datatables.net then you may find that date sorting might not be working as expected depending on the country you're coming from.

Data tables by default doesn't sort according to the following date format: dd/MM/yyyy
In order to get this working correctly, you can override the default implementation with the following code snippet:

        // Override default implementation for date sorting
        $.fn.dataTableExt.oSort['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));
        };

        $.fn.dataTableExt.oSort['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));
        };


Reference: http://datatables.net/forums/comments.php?DiscussionID=2467
Reference: http://datatables.net/forums/comments.php?DiscussionID=1178

No comments:

Post a Comment