javascriptjquerydatetablesorter

sort date field with tablesorter


I'm using the JQuery tablesorter plugin. The table has a column that shows dates in the format 05 Mar 2012. The tablesorter plugin seems to treat this column as text, because it sorts it in the order

How can I sort these dates in chronological order instead?


Solution

  • Parse the date string to a Date, then convert it to milliseconds. Let tablesorter sort the column as numeric.

    $.tablesorter.addParser({ 
        id: 'my_date_column', 
        is: function(s) { 
            // return false so this parser is not auto detected 
            return false; 
        }, 
        format: function(s) { 
            var timeInMillis = new Date.parse(s);
            return timeInMillis;         
        }, 
        // set type, either numeric or text 
        type: 'numeric' 
    }); 
    
    $(function() { 
        $("table").tablesorter({ 
            headers: { 
                6: {       // Change this to your column position
                    sorter:'my_date_column' 
                } 
            } 
        }); 
    });
    

    If you have trouble with Date.parse, see my answer to this question.