Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Datatable date sorting dd/mm/yyyy issue

I am using a Jquery plugin called datatables

Its fantastic, however I cannot get the dates to sort correctly according to the dd/mm/yyyy format.

I have looked at their support formats but none of these fixes seem to work.

Can anybody here help me please?

like image 740
jaget Avatar asked Aug 17 '12 09:08

jaget


People also ask

How to sort Datatable by date?

As stated here you need to include Moment. js and the datatable-moment plugin, then just declare the date format you are using. The plugin will autodetect your date columns and sort it like it should be.

How do you sort DataTables with date in descending order?

date format should be YYYY-MM-DD. sort it *"order": [[ 3, "desc" ]] * and hide the td, th display none.

What is Aocolumns in jquery Datatable?

aoColumnDefs: This array allows you to target a specific column, multiple columns, or all columns, using the aTargets property of each object in the array (please note that aoColumnDefs was introduced in DataTables 1.7).


2 Answers

Update 2020: HTML Solution

Since HTML 5 is so much developed and almost all major browser supporting it. So now a much cleaner approach is to use HTML5 data attributes (maxx777 provided a PHP solution I am using the simple HTML). For non-numeric data as in our scenario, we can use data-sort or data-order attribute and assign a sortable value to it.

HTML

<td data-sort='YYYYMMDD'>DD/MM/YYYY</td> 

Here is working HTML solution

jQuery Solution

Here is working jQuery solution.

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

Add the above code to script and set the specific column with Date values with { "sType": "date-uk" } and others as null, see below:

$(document).ready(function() {     $('#example').dataTable( {         "aoColumns": [             null,             null,             null,             null,             { "sType": "date-uk" },             null         ]     });     }); 
like image 73
Zaheer Ahmed Avatar answered Sep 18 '22 13:09

Zaheer Ahmed


Date Sort - with a hidden element

Convert the date to the format YYYYMMDD and prepend to the actual value (DD/MM/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>DD/MM/YYYY</td>    </tr> </table> 

CSS

#data-table span {     display:none;  } 
like image 29
Anulal S Avatar answered Sep 16 '22 13:09

Anulal S