Search code examples
javascriptsortingviewtablesorter

tableSorter custom date parser doesn't work


I have the following table sorter configuration:

 $(function () {
     $.tablesorter.addParser({
         id: "customDate",
         is: function(s) {
             //return false;
             //use the above line if you don't want table sorter to auto detected this parser
             //else use the below line.
             //attention: doesn't check for invalid stuff
             //2009-77-77 77:77:77.0 would also be matched
             //if that doesn't suit you alter the regex to be more restrictive
             return /\d{1,2}\.\d{1,2}\.\d{1,4} \d{1,2}:\d{1,2}:\d{1,2}/.test(s);
         },
         format: function(s) {
             s = s.replace(/\-/g," ");
             s = s.replace(/:/g," ");
             s = s.replace(/\./g," ");
             s = s.split(" ");
             return $.tablesorter.formatFloat(new Date(s[0], s[1]-1, s[2], s[3], s[4], s[5]).getTime());
         },
         type: "numeric"
     });
    var $table = $('#table')
        .tablesorter({
            headers: {
                        1: { sorter:'customDate' }
                    },
            sortList: [[1,1]],   // sorting(desc) by column with index 1
            dateFormat: 'dd/MM/yyyy HH:mm:ss',
            theme: 'blue',
            widthFixed: true,
            headerTemplate: '{content} {icon}',
            widgets: ['zebra', 'filter'],
            widgetOptions: {
                zebra: ["even", "odd"],
                // filter_anyMatch replaced! Instead use the filter_external option
                // Set to use a jQuery selector (or jQuery object) pointing to the
                // external filter (column specific or any match)
                filter_external: '.search',
                // add a default type search to the first name column
                filter_defaultFilter: {1: '~{query}'},
                // include column filters
                filter_columnFilters: true,
                filter_placeholder: {search: 'Искать...'},
                filter_saveFilters: true,
                filter_reset: '.reset'
            }
        })
        // needed for pager plugin to know when to calculate filtered rows/pages
        .addClass('hasFilters')
        .tablesorterPager({
            container: $(".table-pager"),
            output: '{page} из {filteredPages} ({filteredRows})',
            size: 5
        });
});

but after I run application I see the following table column:
enter image description here

Obviously that column sorted wrong.

Why?


Solution

  • Actually no custom date parser is needed. The dateFormat option should be set to ddmmyyyy. The only settings available for that option are:

    • mmddyyyy
    • ddmmyyyy
    • yyyymmdd

    Once set, the time will be included in the parsing of the date (demo).