Sort by date in datatables

0

I am trying to sort in a datatable by a date field but I do not get it.

I've tried several plugins but none of them work properly.

The example link is a simple datatable where the date field 4 is supposed to format it to the European date and let it order correctly.

I do not know what's wrong.

link

    
asked by Takyo 21.02.2017 в 14:37
source

2 answers

0

Solved.

I used the library moment.js next to the plugin for datatables datetime .

when dealing with dates

$('#example').DataTable( {
columnDefs: [ {
  targets: 4,
  render: $.fn.dataTable.render.moment('YYYY/MM/DD', 'DD-MM-YYYY')
} ]

});

Where the moment () function expects as parameters an input format and a date output format.

With this it arranges the dates correctly and shows them with any format

Solution .

    
answered by 22.02.2017 / 10:15
source
0

I see that you are using moment, but in your case I do not think it is necessary because the date is in YYYY / MM / DD format and in this way it will be ordered correctly since it is ordered, by year, month and day. What to do when the date has a different format? ... you can go through each element tr of the tbody of the table, and take the date and place it in the cell within a span that is not visible (display: none), in YYYYMMDD format.

Example: link

CSS :

#example span {
    display:none; 
}

Javascript :

/* THIS IS ONLY FOR EXAMPLE TO CHANGE THE DATE FORMAT */
var changeDateFormat = $('#example tbody tr').each(function(i,e) {
  var dateTD = $(this).find('td:eq(4)');
  var date = dateTD.text().trim();
  var parts = date.split('/');
  dateTD.text(parts[0]+'/'+parts[2]+'/'+parts[1]);
});

$.when(changeDateFormat).done(function() {
  processDates(); 
})
/* THIS IS ONLY FOR EXAMPLE TO CHANGE THE DATE FORMAT */


function processDates() {
  var process = $('#example tbody tr').each(function(i,e) {
    var dateTD = $(this).find('td:eq(4)');
    var date = dateTD.text().trim();
    var parts = date.split('/');
    dateTD.prepend('<span>'+parts[0]+parts[2]+parts[1]+'</span>');
  });

  $.when(process).done(function() {
    $('#example').DataTable({ "order": [[ 4, "desc" ]]});
  })
}
    
answered by 21.02.2017 в 15:16