使用jQuery表格排序插件对日期列进行排序出现问题

3

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

和之前使用此插件一样,我尝试在JavaScript文件中对其进行排序:

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

然而,它只按照HH:mm排序,这会导致错误的条目(因为它忽略了日期)。是否有另一个特定的日期字符串可以与此一起使用,因为我无法真正更改它,或者是否有一种方法编写自己的自定义解析器并将其与插件一起实现?谢谢!
2个回答

0

dateFormat选项只允许三种设置:"mmddyyyy"(默认值)、"ddmmyyyy""yyyymmdd"

在这种情况下,您需要添加一个自定义列解析器 - 参见此演示文稿,但它仅提供了Sugar.js库的示例。

特别是,请确保加载并使用此解析器,其中包括对Sugar.js和Date.js库的接口。


0

如果有人遇到这种特殊的日期格式,我找到了一个解决方案。原来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'
            }
        }
    });

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接