Datatables sort date and datetime colums

Viewed 397

I have a page with several datatables. Some of the tables have just a date field by which it is sorted, and other tables on that same page have a datetime field. The locale for the date/datetime is German.

I can get Datatables to correctly sort by either date OR datetime but I cannot get it to sort by either. I created this fiddle with a single table: https://jsfiddle.net/r23yfdz8/

$.fn.dataTable.moment( 'DD.MM.YYYY' ); // uncomment this to sort column 1 correctly
    //$.fn.dataTable.moment( 'DD.MM.YYYY HH:mm' ); // this sorts column 2 (date and time) correctly
    $('#example').DataTable()
body {
  font-family: sans-serif;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.datatables.net/1.10.9/js/jquery.dataTables.js"></script>
<link href="https://cdn.datatables.net/1.10.0/css/jquery.dataTables.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.js"></script>
<script src="https://cdn.datatables.net/plug-ins/1.10.19/sorting/datetime-moment.js"></script>
<table id="example">
        <thead>
            <tr>
                <th>date</th>
                <th>date + time</th>
            </tr>
        </thead>
        <tbody>
<tr><td>20.01.2018</td><td>20.01.2018 09:00</td></tr>                 
<tr><td>12.02.2019</td><td>12.02.2019 16:00</td></tr>                 
<tr><td>13.06.2017</td><td>13.06.2017 09:00</td></tr>                 
<tr><td>20.01.2018</td><td>20.01.2018 16:00</td></tr>                 
<tr><td>01.10.2016</td><td>01.10.2016 09:00</td></tr>        
<tr><td>12.10.2018</td><td>12.10.2018 16:00</td></tr>                
<tr><td>21.10.2017</td><td>21.10.2017 09:00</td></tr>           
<tr><td>04.10.2018</td><td>04.10.2018 16:00</td></tr>            
<tr><td>13.10.2018</td><td>13.10.2018 09:00</td></tr>        
<tr><td>01.11.2018</td><td>01.11.2018 16:00</td></tr>        

        </tbody>
    </table>

  1. Click on the second column header "date + time". You'll notice that it sorts the table correctly.
  2. Click on the other column header "date". You'll notice that the date is all over the place and not sorting properly
  3. In the JS code, comment out the second line, and uncomment the first line. After rerunning, the fiddle now sorts column 1 correctly, but fails sorting column 2.

I would love to add a classes ("sort-datetime" and "sort-date") in the DOM to the tags which would then tell datatables how to sort the values but I am not knowledgeable enough to figure out how to do that.

Thanks for the help!

1 Answers

The $.fn.dataTable.moment plug-in can be used multiple times in one table, to accommodate different formats.

If I un-comment both your formatters at the same time, then your demo works OK.

Related