I'm trying to sort dates in my datatable like DD/MM/YYYY
(day, month, year) .
I was following https://datatables.net/plug-ins/sorting/ .
but all the date sorts seem to be deprecated and point to the datetime plugin: https://datatables.net/blog/2014-12-18
I don't seem to be able to get the datetime plugin working to sort. I tried the old way, with date. The initialize looks like this:
var historiektable = $('#dataTableHistoriek').DataTable({
"paging" : false,
"ordering" : true,
"scrollCollapse" : true,
"searching" : false,
"columnDefs" : [{"targets":3, "type":"date"}],
"bInfo": true
});
Without sorting it shows the table results like this:
When I put ordering:true
2 of the 2016 dates appear somewhere else in the list (so, not in order you would expect)
With everything pointing at Moment I thought I needed to sort with that. But I'm not sure how.
I saw $.fn.dataTable.moment('DD.MM.YYYY');
somewhere, but I understood that the fn
doesn't work with this newest version of datatables anymore?
Anyone knows how to sort dates?
DataTable allows you to sort data rows on the client side. There are 2 ways to invoke sorting in the table: By a single click on the header of a column with the enabled sort attribute; By API call ( can be called from some event or action, i.e button click or page load ) of the sort() method.
Using the order initialisation parameter, you can set the table to display the data in exactly the order that you want. The order parameter is an array of arrays where the first value of the inner array is the column to order on, and the second is 'asc' (ascending ordering) or 'desc' (descending ordering) as required.
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).
Use date-eu
sorting plugin to sort dates in the format DD/MM/YY
.
Include the following JS file //cdn.datatables.net/plug-ins/1.10.11/sorting/date-eu.js
and use the code below:
var historiektable = $('#dataTableHistoriek').DataTable({
"paging" : false,
"ordering" : true,
"scrollCollapse" : true,
"searching" : false,
"columnDefs" : [{"targets":3, "type":"date-eu"}],
"bInfo": true
});
For me, using ASP.NET core 3.1 with MVC, I used a data-sort attribute on my <td> for the datatables:
<td data-sort="@(item.DueDateTime.Ticks)">
@Html.DisplayFor(modelItem => item.DueDateTime)
</td>
No plug-ins needed
See this link: https://datatables.net/examples/advanced_init/html5-data-attributes.html
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