1
votes

We are using the Datatables ultimate date/time sorting plugin (https://datatables.net/blog/2014-12-18) to try and sort date columns, but not having any luck getting it to properly sort dates in the right format. When the page loads, the following script is run:

//sets the date format for datatables for sorting purposes
//reference: https://datatables.net/blog/2014-12-18
$.fn.dataTable.moment( 'M/D/YYYY' );

/* Datatables */
$('.datatable').DataTable({
    language : {
        search : "_INPUT_",
        searchPlaceholder : "Search...",
        paginate : {
            "next" : '<i class="fa fa-chevron-right"></i>',
            "previous" : '<i class="fa fa-chevron-left"></i>'
        }
    },
    responsive : {
        details : {
            display : $.fn.dataTable.Responsive.display.childRowImmediate,
            type : 'column'
        }
    },
    order : [0, 'desc'],

  //date sorting
  columnDefs:
  {
    targets: 'date_sortable',
    render: function ( data, type, full, meta ) {
      if(type === 'display'){
         if(data){
            var mDate = moment(data);
            data = (mDate && mDate.isValid()) ? mDate.format("M/D/YYYY") : "";
            console.log('rewrote data to ' + data);
         }
     }
      console.log('date_sortable rendered');
     return data;
   }
  }
});

According to both the Datatables documentation and the details I found on this SO post (DataTables Ultimate date / time sorting plug-in not working with Intl formats), I added date_sortable as a class name on the <th /> element in my HTML, but it looks like the render function isn't called, as my console.log[...] entries never run. I can see in the generated HTML the class is on my <th /> element, and the dates being shown are in the proper format ('n/j/Y', in PHP) so I'm at a total loss.

Everything looks setup correctly, so any tips/pointers here? The date ordering seems to be rather random in nature, with entries that have dates such as 1/6/2016 showing up in the middle (see screenshot), which makes no sense at all.

I will say this table is showing ~2,055 records so is it possibly a performance thing? This isn't currently loading with API calls, so all records are in the generated HTML as a single file.

Dates showing up in the middle

2
it's not random, it's string sorting instead of numeric. in this example, it's sorted in order as 2, 2, 2, 6, 7Jeff Puckett

2 Answers

0
votes

can you look at the unshifted Function in Datatables?

// Add type detection
types.detect.unshift( function ( d ) {
return moment( d, format, locale, true ).isValid() ?
    'moment-'+format :
    null;
} );

if it's the case, you should use this:

$.fn.dataTable.moment('YYYY-M-D');
0
votes

Please try this fiddle (this works with your date format):

`http://jsfiddle.net/Marouen/9qdj53am`

Hope this will help.