Question

My tablesorter table is not sorting dates and empty fields correctly.

I would expect empty fields to be treated like zeros, and be grouped at the top/bottom. Instead I get some dates beneath them.

$('table').tablesorter({
    widthFixed: true,
    // sort on the last name in ascending order
    sortList: [
        [2, 0]
    ],
    dateFormat: "ddmmyyyy",
    emptyTo: "zero",
    sortInitialOrder: "desc",
    headers: {
        3: {
            sorter: "shortDate"
        },
        4: {
            sorter: "shortDate"
        },
        5: {
            sorter: "shortDate"
        },
        6: {
            sorter: "shortDate"
        }
    },
    textExtraction: {
        3: function (n, t, c) {
            return $(n).attr('data-date');
        },
        4: function (n, t, c) {
            return $(n).attr('data-date');
        },
        5: function (n, t, c) {
            return $(n).attr('data-date');
        }
    },
    widgets: ['zebra', 'columns']
});

See the fiddle here. Sort using the 'Date of birth' column.

Was it helpful?

Solution

The "shortDate" parser converts all dates into a time in milliseconds to make date comparison (using a operator or date range with the filter widget) and sorting of dates easier. In order to do that, it uses a javascript function getTime():

The value returned by the getTime method is the number of milliseconds since 1 January 1970 00:00:00 UTC.

So, the issue you are noticing is because non-date cells are treated as having a zero-value, and the date that is not sorting properly is the date "1/1/1930". Entering this date into the javascript console, you'll see this result:

new Date('1/1/1930').getTime()
// returns -1262282400000

Remember, it's the time since 1/1/1970, so the time returns a negative number, which of course is less than zero.

The simplest solution would be to just set the emptyTo option to "min", which sets the value of any empty cells to be a maximum negative number (demo):

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top