Search code examples
jquery-uitablesorter

Column sorting using jQuery tablesorter


I want to sort a column in table which has data like this "yyyy-mm-dd hh:mm:ss S : few more strings". This data is string. I am using jquery.tablesorter 2.0 to sort it based on date. I am not able to sort it. Can you please help...

Amy


Solution

  • You'll need to use one of the date-extract parsers available here, and here is a demo of it working:

    $.tablesorter.addParser({
        id: "extractYYYYMMDD",
        is: function (s) {
            // don't auto detect this parser
            return false;
        },
        format: function (s, table) {
            var date = s.replace(/\s+/g, " ").replace(/[\-.,]/g, "/").match(/(\d{4}[\/\s]\d{1,2}[\/\s]\d{1,2}(\s+\d{1,2}:\d{2}(:\d{2})?(\s+[AP]M)?)?)/i);
            if (date) {
                date = date[0].replace(/(\d{4})[\/\s](\d{1,2})[\/\s](\d{1,2})/, "$2/$3/$1");
                return $.tablesorter.formatFloat((new Date(date).getTime() || ''), table) || s;
            }
            return s;
        },
        type: "numeric"
    });
    
    $('table').tablesorter({
        theme: 'blackice',
        headers: {
            1: {
                sorter: 'extractYYYYMMDD'
            }
        },
        widgets: ['zebra', 'columns']
    });