Jquery tablesort and dates.

By ozhug

having googled for  a date parsers for jquery’s excellent  tablesort and not finding one to do the job i was after. I have posted mine here. (it is of course bigger than required and still includs debugging variables so that you can check the values created as they are sorted using firebug or your favorite jscript debugger)

The dates i wanted to sort were ‘dd MMM yy’  e.g. 3 JAN 09   , 13 FEB 09 etc.

The examples of other tablesort parsers i found failed on empty sorts so I choose to have empty values as max date values . hence the 

var nd = new date('12/12/9999').gettime();

you will of course change this if this does not match your needs. 

so here it is.

 

 $.tablesorter.addParser({
            // set a unique id
            id: 'dates',
            is: function(s) {
                // return false so this parser is not auto detected
                return false;
            },
            format: function(s) {
                // split
            // if s is empty then max date
                var nd = new Date("12/12/9999").getTime();
                if (s != "") {
                    var a = s.split(' ');
                    // get month num
                    a[1] = this.getMonth(a[1]);
                    // glue and return a new date
                    var ad = a[1] + '/' + a[0] + '/' + '20' + a[2];
                    nd = new Date(ad).getTime();
                }
                return nd;
            },
            getMonth: function(s) {
                var m = ['jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug', 'sep', 'oct', 'nov', 'dec'];
                var l = m.length;
                for (var i = 0; i < l; i++) {
                    if (m[i] == s.toLowerCase()) {
                        return (i + 1);
                    }
                }
            },
            // set type, either numeric or text
            type: 'numeric'
        });

Tags: ,

Leave a Reply