Home > JavaScript, MVC > TableSorter – Creating a Custom ‘TimeSpan’ Parser

TableSorter – Creating a Custom ‘TimeSpan’ Parser

October 22, 2010

Activities ordered incorrectly by string comparison.In an application we’re working on, I needed a way to sort a string-based time span returned by my view. The problem was separating it out so that AMs came before PMs.

tablesorter allows adding custom parsers to columns. Along with a simple regular expression, the parser can swap the time format around (AM 10:30 rather than 10:30 AM) and sort accordingly.

The custom parser code:

 
$.tablesorter.addParser({ 
    id: 'timeSpan', 
    is: function (s) { return false; }, 
    format: function (s) { 
        var re = /([0-2]?[0-9]:[0-5][0-9])|(AM|PM)/; 
        var matches = re.exec(s); 
        return matches[0,1] + " " + matches[0,0]; 
    }, 
    type: 'numeric' }); 

Adding the parser into TableSorter:

$('#my-table').tablesorter({ 
    sortList: [[1, 0], [0, 0]], 
    headers: { 
        0: { sorter: 'timeSpan' }, 
        1: { sorter: 'dayOfWeek' }, 
        6: { sorter: false } 
    }, 
    widgets: ['zebra'] 
}); 

Now, everything looks like it should:

Activities ordered correctly by start time.

Categories: JavaScript, MVC Tags: , ,
%d bloggers like this: