Skip to content Skip to sidebar Skip to footer

Datatables - How To Sort By Date (dd.mm.yyyy)

I have a table with multiple columns. 1 column contains date in format dd.mm.yyyy (example: 26.05.2021). I'm trying to achieve a default sorting by date. My table looks like this:

Solution 1:

Because you have two different date/time formats in your table (one for the column 2 date and one for the column 3 time), I recommend using the ultimate date/time sorting plug-in.

You need these extra resources in the page header:

<scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.26.0/moment.min.js"></script><scriptsrc="https://cdn.datatables.net/plug-ins/1.10.25/sorting/datetime-moment.js"></script>

Then, in the body script, you can define the two formats you need:

$.fn.dataTable.moment( 'DD.MM.YYYY' );
$.fn.dataTable.moment( 'HH:mm' );

Formatting options for those two strings are documented here as part of the moment.js library.

DataTables takes care of the rest.

It looks through the list of date/time formats you have provided and automatically fits the correct format to the relevant column data. It then uses that format to ensure the data is sorted chronologically, while leaving the display format unchanged.

A demo:

<!doctype html><html><head><metacharset="UTF-8"><title>Demo</title><scriptsrc="https://code.jquery.com/jquery-3.5.1.js"></script><scriptsrc="https://cdn.datatables.net/1.10.22/js/jquery.dataTables.js"></script><linktype="text/css"href="https://cdn.datatables.net/1.10.22/css/jquery.dataTables.css"><linktype="text/css"href="https://datatables.net/media/css/site-examples.css"><scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.26.0/moment.min.js"></script><scriptsrc="https://cdn.datatables.net/plug-ins/1.10.25/sorting/datetime-moment.js"></script></head><body><divstyle="margin: 20px;"><tableid="example"class="display dataTable cell-border"style="width:100%"><thead><tr><th>Title</th><th>Date</th><th>Time</th><th>Notes</th></tr></thead><tbody><tr><td>Some Text A</td><td>21.06.2021</td><td>15:10</td><td>Some Text 2</td></tr><tr><td>Some Text B</td><td>22.07.2020</td><td>16:00</td><td>Some Text XYZ</td></tr><tr><td>Some Text C</td><td>22.07.2020</td><td>15:59</td><td>Some Text XYZ</td></tr></tbody><tfoot><tr><th>Title</th><th>Date</th><th>Time</th><th>Notes</th></tr></tfoot></table></div><scripttype="text/javascript">

$(document).ready(function() {

  $.fn.dataTable.moment( 'DD.MM.YYYY' );
  $.fn.dataTable.moment( 'HH:mm' );

  $('#example').DataTable( {
    order: [
      [1, "desc"],
      [2, "desc"]
    ],
  } );

} );

</script></body></html>

Post a Comment for "Datatables - How To Sort By Date (dd.mm.yyyy)"