Search code examples
javascriptjqueryjquery-pluginstablesorter

Jquery: TableSorter- Date with specic format is not working


I am using Tablesorter plugin to sort the table . fourth column is date fields having format :

-->30 Jan 2013

-->01 Feb 2013

when i try to sort format it gives wrong sorting.

My View page:(one of the date column )

<td onclick="viewTrainingeDetails(${privateTrainingInstance?.id})"><g:formatDate format="dd MMM yyyy" date="${privateTrainingInstance?.startDate}" /></td>

jquery

 $(function() {
         $("#myTable").tablesorter(); 
   });

Solution

  • Try adding this custom parser (demo):

    $.tablesorter.addParser({
        id: "date",
        is: function (s) {
            return false;
        },
        format: function (s, table) {
            return new Date(s).getTime() || '';
        },
        type: "numeric"
    });
    

    then initialize the plugin like this:

    $('table').tablesorter({
        headers: {
                5: { sorter: 'date' }
            }
    });
    

    Update: for best results, make sure you are returning a valid date:

    $.tablesorter.addParser({
        id: "date",
        is: function (s) {
            return false;
        },
        format: function (s, table) {
            var date = new Date(s);
            return date instanceof Date && isFinite(date) ? date.getTime() : '';
        },
        type: "numeric"
    });