Gillian
Gillian

Reputation: 411

tablesorter, wont sort by date correctly

Does the tablesorter behave differently if there is whitespace about?

I'm pretty new to tablesorter but I was asked quickly to add it to a customers site (specifically to allow them to sort by date published). As far as i am aware, the date (eg. 14 May 2012) is read as text, so I need to add a parser to change this to numeric in order for it to sort properly. (eg. 14052012)

This I have (currently using code written by the other developer - resides in the tablesorter.js).

$.tablesorter.addParser({
id: 'dayMonthYear',
is: function(s) {
    return false;
},
format: function(s) {           

    var date = s.match(/^(\d{1,2})[ ](\w{3})[ ](\d{4})$/);
    var day = String(date[1]);
    if (day.length == 1) {
        day = "0" + day;
    }        

    var month = monthNames[date[2]];
    var year = date[3];
    var sortableDate = '' + year + month + day;
    return sortableDate;
},
type: 'numeric'  
});

var monthNames = {};
monthNames["Jan"] = "01";
monthNames["Feb"] = "02";
monthNames["Mar"] = "03";
monthNames["Apr"] = "04";
monthNames["May"] = "05";
monthNames["Jun"] = "06";
monthNames["Jul"] = "07";
monthNames["Aug"] = "08";
monthNames["Sep"] = "09";
monthNames["Oct"] = "10";
monthNames["Nov"] = "11";
monthNames["Dec"] = "12";

I also have this placed in the html page

$("table#searchresults").tablesorter ({
    headers: {
        0: {sorter:'dayMonthYear'}
    }
});

Although I've seen this code working, it doesnt seem to work for me. The month is still being read as text.

Any ideas? The only thing I can see different between the working demo and my site, is that the table has loads of whitespace kicking about, could this be an issue?


EDIT: Just found this, http://beausmith.com/blog/custom-date-sorting-for-jquery-tablesorter-plugin/, looks familiar to the above code. Hopefuly it helps...

Upvotes: 3

Views: 1204

Answers (1)

Gillian
Gillian

Reputation: 411

Got it working.. phew

$.tablesorter.addParser({
id: 'dayMonthYear',
is: function(s) {
    return false;
},
format: function(s) {       

    s = $.trim(s.replace(/\s+/g, ' '));


    var date = s.match(/^(\d{1,2})[ ](\w{3})[ ](\d{4})$/);
    var day = String(date[1]);
    if (day.length == 1) { day = "0" + day;}        
    var month = monthNames[date[2]];
    var year = date[3];

    return sortableDate = '' + year + month + day;
},
type: 'numeric'  
});
var monthNames = {};
monthNames["Jan"] = "01";
monthNames["Feb"] = "02";
monthNames["Mar"] = "03";
monthNames["Apr"] = "04";
monthNames["May"] = "05";
monthNames["Jun"] = "06";
monthNames["Jul"] = "07";
monthNames["Aug"] = "08";
monthNames["Sep"] = "09";
monthNames["Oct"] = "10";
monthNames["Nov"] = "11";
monthNames["Dec"] = "12";

Upvotes: 3

Related Questions