Tablesorter ordering dates and empty dates incorrectly

萝らか妹 提交于 2019-12-11 10:04:10

问题


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.


回答1:


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):



来源:https://stackoverflow.com/questions/22900822/tablesorter-ordering-dates-and-empty-dates-incorrectly

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!