使用 jQuery table-sorter 插件对日期列进行排序的问题

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

我为我的 table 实现了 jQuery TableSorter 插件,一切正常,除了特定的列,它包含以下格式:HH:mm, dd.MM,例如 09:45, 15.1115:48, 16.11.

正如我之前使用此插件所做的那样,我尝试在 javascript 文件中对 tables:

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

但是,它只按 HH:mm 排序,这会导致错误的条目(因为它忽略了日期)。是否有另一个特定的日期字符串适用于此,因为我无法真正更改它,或者是否有办法编写我自己的自定义解析器并使用插件实现它?谢谢!

dateFormat option 只允许 3 个设置:"mmddyyyy"(默认)、"ddmmyyyy""yyyymmdd"

在这种情况下,您需要添加 custom column parser - see this demo,但它只有 Sugar.js 库的示例。

特别是,确保加载和使用 this parser,其中包括 Sugar.js 和 Date.js 库的接口。

如果有人偶然发现这种特定的日期格式,我会找到解决方案。事实证明,TableSorter 插件允许添加自定义解析器,您可以满足您的需要。有关此的更多信息,请参见此处 - https://mottie.github.io/tablesorter/docs/example-parsers.html.

在这个特定的例子中,它看起来像这样,现在有效并且列是可排序的:

$.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'
            }
        }
    });