Search code examples
javascriptjqueryhtmltablesorter

Issue with sorting date columns with the jQuery table-sorter plugin


I implemented the jQuery TableSorter add-on for my table and all works fine, except that specific column, which contains the following format: HH:mm, dd.MM, for example 09:45, 15.11 or 15:48, 16.11.

As I have done before with this plug-in, I tried this is in the javascript file, which sorts the tables:

$(function() 
    $(".my-table").tablesorter({
      sortList: [[1,0]], // sorting on the second column
      dateFormat : "HH:mm, dd.MM"
    });
  });

However, it only sorts by the HH:mm, which causes wrong entries (because it ignores the dates). Is there another specific datestring that would work with this, as I can't really change it, or is there a way to write my own custom parser and implement it with the plug-in? Thank you!


Solution

  • I reached a solution if anyone stumbles upon this specific date format. It turns out that the TableSorter plug-in allows for adding a custom parser, that you can suit for your needs. More information about this here - https://mottie.github.io/tablesorter/docs/example-parsers.html.

    In this specific case, it looked like this, which now works and the column is sortable:

    $.tablesorter.addParser({
            id: 'custom_date_parser',
            // Auto-detection
            is: function(date) {
                return false;
            },
            // Normalize data and allow sorting for this specific type
            format: function(date) {
                // get current year
                var current_year = new Date().getFullYear()
    
                // obtain date values from column
                // current format HH:mm, dd.MM
                var hour = date.slice(0, 2);
                var minutes = date.slice(3, 5);
                var day = date.slice(7, 9);
                var month = date.slice(10, 12);
    
                // convert to date object
                return date = new Date(current_year, month - 1, day, hour - 1, minutes)
            },
            parsed: false,
            // Type of sorting to use
            type: 'numeric'
        });
    
    // Perform the sorting
        $("#table-name").tablesorter({
            // apply custom parser only to the second column
            headers: {
                1: {
                    sorter: 'custom_date_parser'
                }
            }
        });