Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery DataTables plugin: Sort German date

I use jQuery DataTables plugin and my problem is that my German date does not get ordered correctly. It has the following format: dd.mm.YYYY HH:iih

Here comes my code:

JSFIDDLE:

https://jsfiddle.net/uxaLn1e3/3/

HTML:

    <table id="my-table">
   <thead>
      <th>Nr. </th>
      <th>Date</th>
      <th>Name</th>
   </thead>
   <tr>
      <td>1</td>
      <td>27.08.2015 19:00h</td>
      <td>Carl</td>
   </tr>
   <tr>
      <td>2</td>
      <td>10.02.2016 14:00h</td>
      <td>Alan</td>
   </tr>
   <tr>
      <td>3</td>
      <td>07.12.2015 21:00h</td>
      <td>Bobby</td>
   </tr>
</table>

JS (updated, with ajax):

     $('#my-table').DataTable({
            "ajax": 'my_url',
            "columns": [
                {"data": "nr"},
                {"data": "date"},
                {"data": "name"}
            ],
                "autoWidth": false,
                "order": [],
                "fnCreatedRow": function( nRow, aData, iDataIndex ) {
                   var dateFull = aData.date;
                   var dateFullItems = dateFull.split(' ');
                   var dateDatum = dateFullItems[0];
                   var dateDatumItems = dateDatum.split('.');
                  var dateTime = dateFullItems[1];
                  var dateFormat = dateDatumItems[2] + '-' + dateDatumItems[1] + '-' + dateDatumItems[0] + 'T' + dateTime + ':00Z'; 

                  $(nRow).find('td:nth-of-type(2)').attr('data-sort', dateFormat);
            },
            });

What adjustments do I need to do in my JS for the sorting of date to work?

like image 608
Max Avatar asked Oct 16 '25 14:10

Max


1 Answers

Add a data-sort attribute to the td having the date stored in a Standard Format (I have used ISO Format here i.e. YYYY-MM-DDTHH:ii:ssZ ):

<tr>
  <td>1</td>
  <td data-sort="2015-08-27T19:00:00Z">27.08.2015 19:00h</td>
  <td>Carl</td>
</tr>
<tr>
  <td>2</td>
  <td data-sort="2016-02-10T14:00:00Z">10.02.2016 14:00h</td>
  <td>Alan</td>
</tr>
<tr>
  <td>3</td>
  <td data-sort="2015-12-07T21:00:00Z">07.12.2015 21:00h</td>
  <td>Bobby</td>
</tr>

Now datatables will consider this data-sort value instead of the html of td to sort the columns.

Live Fiddle

Even if you are creating the table dynamically you can achieve this in two ways:

A. Add a data-sort attribute while generating the html.

B. Add a data-sort after the datatable is created using jQuery and then reinit the datatable.

like image 99
void Avatar answered Oct 18 '25 16:10

void