2

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

  • 05 Mar 2012
  • 06 Jan 2012
  • 07 Dec 2012

How can I sort these dates in chronological order instead?

Dónal
  • 185,044
  • 174
  • 569
  • 824

4 Answers4

3

You can also add a hidden span tag before your date in numerical format (yyyymmdd). This text will come first and be used for sorting but it will be hidden from sight and only show the format you want.

    <td><span style="display:none">20130923</span>23rd September 2013</td>
compsmart
  • 161
  • 1
  • 3
  • this didn't work for me. but I added a class to the span instead, with these properties: position: absolute; top: 0px; visibility: hidden;. It still allowed the sorter to read the text, without displaying it to the end user. – user417669 Dec 20 '13 at 03:03
  • This is a nice and simple solution +1 – karel Jun 03 '16 at 20:29
3

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.

Community
  • 1
  • 1
Vik David
  • 3,640
  • 4
  • 21
  • 29
1

You will need to use addParser method and create a parser that converts your string to date object.

follow example on plugin site http://tablesorter.com/docs/example-parsers.html

If need a date parser:

http://www.datejs.com/

EDIT: your dates convert easily in format shown:

 console.log(new Date('05 Mar 2012'))//  logs proper date object
charlietfl
  • 170,828
  • 13
  • 121
  • 150
0

Haven't used tablesorter in a while but I seem to remember having a similar issue with UK dates.

You can add a dateformat parameter to the tablesorter plugin with your custom dateformat.

dateFormat: 'dd MMM yyyy' 
Dónal
  • 185,044
  • 174
  • 569
  • 824
munnster79
  • 578
  • 3
  • 16
  • I tried this, but it made no difference. Do I need to somehow indicate which columns contain dates? – Dónal Mar 05 '12 at 15:28