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?
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.
date format should be YYYY-MM-DD. sort it *"order": [[ 3, "desc" ]] * and hide the td, th display none.
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).
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
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 ] }); });
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; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With