user4199101
user4199101

Reputation: 43

Sorting time hh:mm:ss with tablesorter plugin

I'm using the tablesorter plugin and I have a column to sort in the format hh:mm:ss. sorter: 'time' does not work. Is there a way to sort this column? Thanks

I have tried it like this but it does not sort the colum

ts.addParser({
id: "customDate",
is: function(s) {
    return false;        
},
format: function(s) {
    s = s.replace(/:/g," ");
    s = s.split(" ");
    return $.tablesorter.formatFloat(new Date(s[0], s[1]-1, s[2]).getTime()+parseInt(s[3]));
},
type: "numeric"

});

Upvotes: 1

Views: 817

Answers (1)

Mottie
Mottie

Reputation: 86443

There is already a built-in time parser for tablesorter, but it looks for an "AM" or "PM".

But it looks like you need to sort using timer times (hh:mm:ss, or whatever it's called).

The following parser code looks a bit convoluted, but it should cover circumstances where a column only contains seconds (ss), or minutes & seconds (mm:ss).

The maxDigits setting is needed because the parser is basically adding leading zeros on to the value to keep the values consistent, so 10:30:40 becomes 010030040 (when maxDigits is set to 3).

Anyway, here is a demo:

$(function () {

    // change maxDigits to 4, if values go > 999
    // or to 5 for values > 9999, etc.
    var maxDigits = 3;

    $.tablesorter.addParser({
        id: "times",
        is: function (s) {
            return false;
        },
        format: function (s) {
            // prefix contains leading zeros that are tacked
            var prefix = new Array(maxDigits + 1).join('0'),
                // split time into blocks
                blocks = s.split(/\s*:\s*/),
                len = blocks.length,
                result = [];
            // add values in reverse, so if there is only one block
            // (e.g. "10"), then it would be the time in seconds
            while (len) {
                result.push((prefix + (blocks[--len] || 0)).slice(-maxDigits));
            }
            // reverse the results and join them
            return result.length ? result.reverse().join('') : s;
        },
        type: "text"
    });

    $('table').tablesorter({
        theme: 'blue',
        headers: {
            3: {
                sorter: 'times'
            }
        }
    });
});

I'm not sure if this matters to you, but there is also a "duration" parser available that allows adding labels after the times (e.g. 10y 30d 6h 10m) - see this demo

Upvotes: 1

Related Questions