How to sort by Date with DataTables jquery plugin?
Click on the "show details" link under Date (dd/mm/YYY), then you can copy and paste that plugin code provided there
Update: I think you can just switch the order of the array, like so:
jQuery.fn.dataTableExt.oSort['us_date-asc'] = function(a,b) {
var usDatea = a.split('/');
var usDateb = b.split('/');
var x = (usDatea[2] + usDatea[0] + usDatea[1]) * 1;
var y = (usDateb[2] + usDateb[0] + usDateb[1]) * 1;
return ((x < y) ? -1 : ((x > y) ? 1 : 0));
};
jQuery.fn.dataTableExt.oSort['us_date-desc'] = function(a,b) {
var usDatea = a.split('/');
var usDateb = b.split('/');
var x = (usDatea[2] + usDatea[0] + usDatea[1]) * 1;
var y = (usDateb[2] + usDateb[0] + usDateb[1]) * 1;
return ((x < y) ? 1 : ((x > y) ? -1 : 0));
};
All I did was switch the __date_[1]
(day) and __date_[0]
(month), and replaced uk
with us
so you won't get confused. I think that should take care of it for you.
Update #2: You should be able to just use the date object for comparison. Try this:
jQuery.fn.dataTableExt.oSort['us_date-asc'] = function(a,b) {
var x = new Date(a),
y = new Date(b);
return ((x < y) ? -1 : ((x > y) ? 1 : 0));
};
jQuery.fn.dataTableExt.oSort['us_date-desc'] = function(a,b) {
var x = new Date(a),
y = new Date(b);
return ((x < y) ? 1 : ((x > y) ? -1 : 0));
};
You should make use of the HTML5 Data Attributes. https://www.datatables.net/examples/advanced_init/html5-data-attributes.html
Just add the data-order element to your td element.
No plugins required.
<table class="table" id="exampleTable">
<thead>
<tr>
<th>Firstname</th>
<th>Sign Up Date</th>
</tr>
</thead>
<tbody>
<tr>
<td>Peter</td>
<td data-order="2015-11-13 12:00">13. November 2015</td>
</tr>
<tr>
<td>Daniel</td>
<td data-order="2015-08-06 13:44">06. August 2015</td>
</tr>
<tr>
<td>Michael</td>
<td data-order="2015-10-14 16:12">14. October 2015</td>
</tr>
</tbody>
</table>
<script>
$(document).ready(function() {
$('#exampleTable').DataTable();
});
</script>
I realize this is a two year old question, but I still found it useful. I ended up using the sample code provided by Fudgey but with a minor mod. Saved me some time, thanks!
jQuery.fn.dataTableExt.oSort['us_date-asc'] = function(a,b) {
var x = new Date($(a).text()),
y = new Date($(b).text());
return ((x < y) ? -1 : ((x > y) ? 1 : 0));
};
jQuery.fn.dataTableExt.oSort['us_date-desc'] = function(a,b) {
var x = new Date($(a).text()),
y = new Date($(b).text());
return ((x < y) ? 1 : ((x > y) ? -1 : 0));
};
Date Sort - with a hidden element
Convert the date to the format YYYYMMDD and prepend to the actual value (MM/DD/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>MM/DD/YYYY</td>
</tr>
</table>
CSS
#data-table span {
display:none;
}