2

I am using jquery datatable plugin to list down the data in my java spring MVC web application. One of my fields in the table contains date with timestamp. In that, I have been trying to sort the data elements. When I try to sort the elements in field containing date with timestamp, sorting does not work.

I am using the following jquery for datatable initialization

 $('.swcm-dt-basic').dataTable( {
        "responsive": true,
        "order": \[\],
        "language": {
            "paginate": {
              "previous": '<i class="swcm-psi-arrow-left"></i>',
              "next": '<i class="swcm-psi-arrow-right"></i>'
            }
        }
    } );

The following image shows the issue Error in Sorting

3 Answers 3

4

SOLUTION 1

Use data-order attribute for td element that contains sortable timestamp. For example:

<td data-order="2016-12-02 21:28:41">12/02/2016 21:28:41</td>

See this example for code and demonstration.

SOLUTION 2

Use sorting plugins like datetime-moment for any date format or date-euro if your date is in DD/MM/YYYY HH:MM:SS format.

If your date is in MM/DD/YYYY HH:MM:SS, you can use the following code:

jQuery.extend( jQuery.fn.dataTableExt.oSort, {
    "date-us-pre": function ( a ) {
        var x;
 
        if ( $.trim(a) !== '' ) {
            var frDatea = $.trim(a).split(' ');
            var frTimea = (undefined != frDatea[1]) ? frDatea[1].split(':') : [00,00,00];
            var frDatea2 = frDatea[0].split('/');
            x = (frDatea2[2] + frDatea2[0] + frDatea2[1] + frTimea[0] + frTimea[1] + frTimea[2]) * 1;
        }
        else {
            x = Infinity;
        }

        return x;
    },
 
    "date-us-asc": function ( a, b ) {
        return a - b;
    },
 
    "date-us-desc": function ( a, b ) {
        return b - a;
    }
} );

$(document).ready(function(){
   $('#example').dataTable( {
      columnDefs: [
         { type: 'date-us', targets: 0 }
      ]
   } );
}
Sign up to request clarification or add additional context in comments.

Comments

0

If you are looking for just a simple solution to sort that column, which I am not sure from your question, use yyyymmdd hh:mm:ss format. But if you are specific on mm/dd/yyyy hh:mm:ss format, try the following suggestions: https://stackoverflow.com/a/25359251/3483409 https://stackoverflow.com/a/33568433/3483409

Comments

0

You can use something like this.

$('#example').dataTable( {
     columnDefs: [
       { type: 'de_datetime', targets: 0 },
       { type: 'de_date', targets: 1 }
     ]
  } );

for more information you can visit https://datatables.net/plug-ins/sorting/date-de

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.