Thursday, August 11, 2011

Tablesorter custom parser for date format "d-mmm-yyyy h:mm:ss A"

I now need to sort full timestamps in my preferred format so needed another parser the handle dates like:
    "2-Mar-2010 2:12:13 PM".

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: 'drbDateLong',
      is: function(s) { return false; }, 
      format: function(s) {
        s = '' + s; //Make sure it's a string
        //                  d(1-31) - mmm(Jan-Dec) - yyyy    h(1-12):  mm   :  ss     AM/PM 
        var hit = s.match(/(\d{1,2})-([A-Za-z]{3})-(\d{4}) (\d{1,2}):(\d{2}):(\d{2}) ([A-Za-z]{2})/);
        if (hit && hit.length == 8) {
          if(hit[1].length == 1) { hit[1] = "0"+hit[1]; }
          if(hit[7].toUpperCase() == "PM") { hit[4] = String(parseInt(hit[4])+12); }
          if(hit[4].length == 1) { hit[4] = "0"+hit[4]; }
          return hit[3]+months[hit[2].toUpperCase()]+hit[1]+hit[4]+hit[5]+hit[6];
        } else { return s; }
      },
      type: 'text'
    });

Again, many thanks to Christian Bach and this post by MorningZ.

No comments:

Post a Comment