Search code examples
javascriptjquerytablesorter

jQuery Tablesorter Custom Date Parser


I've searched through the forums and could not seem to find a similar situation to mine, so I wondered if someone here could possibly help.

I have a dynamically-generated table that contains a column with 'release dates' that I would like to sort by date. The problem is that the date values in this column are preceded by the number of releases in brackets.

Possible values in this column will be the complete date and time stamp with AM/PM designator and preceded by the number or releases, or the word 'None.' For example, these are some actual values from the data table:

None
[1] 1/24/2008 5:53:35 PM    
[1] 7/31/2012 11:32:50 AM   
[10] 3/29/2013 2:59:04 PM   
[3] 12/17/2014 2:43:27 PM   
[1] 1/9/2015 6:48:31 PM
[4] 1/9/2015 7:02:09 PM 
[4] 1/30/2015 11:25:20 AM   
[2] 12/27/2016 12:32:02 PM  
[2] 11/16/2017 11:04:22 AM

Because of the additional characters preceding the date, the built-in sorting doesn't function correctly. I added the following parameter in my code to assign a custom parser to the column, which is the third one listed in the table:

headers: 2: { sorter: 'DateParser' }

And, here's the code for my parser to strip out the leading characters, leaving only the date and time:

$.tablesorter.addParser({
    id: 'DateParser',
    is: function(s) {
        return false;
    },
    format: function(s) {
        var datesort;
        if (s != "None") {
            var livereleasedate = s.split(']');
            var datetime = livereleasedate[1].trim();
            console.log(datetime);
            datesort = datetime;
        }
        else {
            datesort = s;
        }
        return datesort;
    },
    type: 'text'
});

Unfortunately, this still doesn't work quite right. It appears that the month and day values are being sorted in proper order, but the rest of the string is not. When I click on the column header to sort the values I get this:

[1] 1/9/2015 6:48:31 PM
[4] 1/9/2015 7:02:09 PM
[1] 1/24/2008 5:53:35 PM
[4] 1/30/2015 11:25:20 AM
[10] 3/29/2013 2:59:04 PM
[1] 7/31/2012 11:32:50 AM
[2] 11/16/2017 11:04:22 AM
[3] 12/17/2014 2:43:27 PM
[2] 12/27/2016 12:32:02 PM
None

Any suggestions for how to solve this?

Thanks in advance.


Solution

  • Try the extractMMDDYYYY parser available in the parser-date-extract.js file that is part of my fork of tablesorter. This parser should work with the original tablesorter... demo

    $(function() {
      $('table').tablesorter({
        theme: 'blue',
        headers: {
          0: { sorter: "extractMMDDYYYY" }
        }
      });
    });