Sunday, 24 May 2015

How to sort date in jQuery datatable

Hi Guys,

I got a task today to implement the date sorting in jQuery Data table. Name and plain number sorting are available in jQuery by default. But, there is nothing available in jQuery to sort the dates as the dates can be in any format. I have picked up an example where the date format is dd/mm/yyyy.

Perform the following steps to achieve custom sorting:
1) Need to tell datatable that the particular column is going to implement the custom sorting by defining sType in the aoColumns attribute.
2) Then implement both the ascending and descending methods to perform the sorting in the respective orders.

Data Table definition:

var newTable = $('#newReqTable').dataTable({
  "bProcessing" : true,
  "bAutoWidth" : true,
  "bPaginate" : true,
  "bInfo" : false,
  "sScrollY":"450px",
  "sScrollX":"100%", 
  "bScrollCollapse":true,
  "aoColumns": [
                { "sType": "ukdate" },
                null,
                null,
                null,
                null
            ]
 });

Add method for Ascending order:

When the strings a and b are formed, make sure that it should be concatenated likewise Year+Month+Date. This is because, the date format for US is MM/DD/YYYY whereas UK is DD/MM/YYYY.

jQuery.fn.dataTableExt.oSort['ukdate-asc']  = function(a,b) {
  
     var usDatea = a.split('-'); 
     var usDateb = b.split('-'); 

     var x = (usDatea[2] + usDatea[1] + usDatea[0]) * 1;
     var y = (usDateb[2] + usDateb[1] + usDateb[0]) * 1;
     console.log('ASC - first - '+a+', second - '+b+', X - '+x+',Y - '+y);
     return ((x < y) ? -1 : ((x > y) ?  1 : 0));
 };

Add method for Descending order:

jQuery.fn.dataTableExt.oSort['ukdate-desc'] = function(a,b) {
  
  var usDatea = a.split('-'); 
     var usDateb = b.split('-'); 


     var x = (usDatea[2] + usDatea[1] + usDatea[0]) * 1;
     var y = (usDateb[2] + usDateb[1] + usDateb[0]) * 1;
     console.log('DESCCCC - first - '+a+', second - '+b+', X - '+x+',Y - '+y);
     return ((x < y) ? 1 : ((x > y) ?  -1 : 0));
 };

References:

From Datatable

Example on Time sorting

Different way of Sorting

No comments:

Post a Comment