Thursday, April 24, 2008

Sorting time spans with jQuery Tablesorter

I've been working a little with Christian Bach's nifty Tablesorter plugin for jQuery, and I'd like to share some cool stuff I've learned.

I wanted to sort a column of time spans formatted like this: "2 days 15:11:06". I wrote a custom parser and ended up with this:

$.tablesorter.addParser({
    id: 'timespan',
    is: function(s) { return false; }, // don't auto detect
    format: function(s) { return s.replace(/\D/g,""); },
    type: 'numeric'
});

And the usage:

$("#mytable").tablesorter({
    headers : {
        2 : 'timespan' // the 3rd column is a time span
    }
});

All it's doing is removing all non-digits and asking for a numeric comparison. It should even work equally well for "0 days 02:30:00" and for "02:30:00", since leading zeros don't affect the sorting :-)

4 comments:

  1. Thanks for sharing and happy tablesorting!

    ReplyDelete
  2. Very cute.
    The way you did it sounded fishy to me at first, but on more reflection seems right and rather elegant. I couldn't find holes in it assuming fixed digits (you always show 6 minutes as 06).

    ReplyDelete
  3. This didnt work for me, still sorting alphabetic.

    11.22:45:41.4951386
    11.22:45:41.4951386
    11.22:45:41.4951386
    4.19:13:11.0081386
    5.01:52:33.7881386
    5.01:52:33.7881386

    ReplyDelete