Sorting time hh:mm:ss with tablesorter plugin

后端 未结 1 970
野趣味
野趣味 2021-01-24 09:22

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 t

相关标签:
1条回答
  • 2021-01-24 09:54

    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

    0 讨论(0)
提交回复
热议问题