Monday, July 25, 2011

Tablesorter modification to handle D-MMM-YYYY date format

I have a strong preference when it comes to date formats and that is D-MMM-YYYY. By using the 3 character abbreviation for the month and a four digit year it is impossible to misinterpret any date.

Our website makes routine use of Christian Bach's tablesorter but by default it does not handle my preferred date format.  Adding the following code resolved this issue:
    var months = {}; 
    months["JAN"] = "01"; 
    months["FEB"] = "02"; 
    months["MAR"] = "03"; 
    months["APR"] = "04"; 
    months["MAY"] = "05"; 
    months["JUN"] = "06"; 
    months["JUL"] = "07"; 
    months["AUG"] = "08"; 
    months["SEP"] = "09"; 
    months["OCT"] = "10"; 
    months["NOV"] = "11"; 
    months["DEC"] = "12";  
    ts.addParser({ 
        id: 'drbDate', 
        is: function(s) { return false; },  
            format: function(s) { 
              s = '' + s; //Make sure it's a string 
              //                  d(1-31) - mmm(Jan-Dec) - yyyy 
              var hit = s.match(/(\d{1,2})-([A-Za-z]{3})-(\d{4})/); 
              if (hit && hit.length == 4) { 
                if(hit[1].length == 1) { hit[1] = "0"+hit[1]; } 
                return hit[3]+months[hit[2].toUpperCase()]+hit[1]; 
              } else { return s; } 
            }, type: 'text' 
    });

Many thanks to Christian Bach and this post by MorningZ.