【问题标题】:sort date field with tablesorter使用 tablesorter 对日期字段进行排序
【发布时间】:2012-03-05 14:39:44
【问题描述】:

我正在使用 JQuery tablesorter 插件。该表有一列以05 Mar 2012 格式显示日期。 tablesorter 插件似乎将此列视为文本,因为它按顺序对其进行排序

  • 2012 年 3 月 5 日
  • 2012 年 1 月 6 日
  • 2012 年 12 月 7 日

如何改为按时间顺序对这些日期进行排序?

【问题讨论】:

    标签: javascript jquery date tablesorter


    【解决方案1】:

    将日期字符串解析为日期,然后将其转换为毫秒。让 tablesorter 将列排序为数字。

    $.tablesorter.addParser({ 
        id: 'my_date_column', 
        is: function(s) { 
            // return false so this parser is not auto detected 
            return false; 
        }, 
        format: function(s) { 
            var timeInMillis = new Date.parse(s);
            return timeInMillis;         
        }, 
        // set type, either numeric or text 
        type: 'numeric' 
    }); 
    
    $(function() { 
        $("table").tablesorter({ 
            headers: { 
                6: {       // Change this to your column position
                    sorter:'my_date_column' 
                } 
            } 
        }); 
    });
    

    如果您在使用 Date.parse 时遇到问题,see my answer to this question

    【讨论】:

      【解决方案2】:

      您还可以在日期之前以数字格式 (yyyymmdd) 添加隐藏的跨度标签。此文本将首先出现并用于排序,但它将隐藏在视线之外,仅显示您想要的格式。

          <td><span style="display:none">20130923</span>23rd September 2013</td>
      

      【讨论】:

      • 这对我不起作用。但我改为在 span 中添加了一个类,具有以下属性: position: absolute;顶部:0px;可见性:隐藏;。它仍然允许分拣机读取文本,而不向最终用户显示。
      • 这是一个不错且简单的解决方案 +1
      【解决方案3】:

      您将需要使用 addParser 方法并创建一个解析器,将您的字符串转换为日期对象。

      按照插件网站上的示例 http://tablesorter.com/docs/example-parsers.html

      如果需要日期解析器:

      http://www.datejs.com/

      编辑:您的日期可以轻松转换为所示格式:

       console.log(new Date('05 Mar 2012'))//  logs proper date object
      

      【讨论】:

        【解决方案4】:

        有一段时间没有使用 tablesorter,但我似乎记得在英国日期时遇到过类似的问题。

        您可以使用自定义日期格式将 dateformat 参数添加到 tablesorter 插件。

        dateFormat: 'dd MMM yyyy' 
        

        【讨论】:

        • 我试过这个,但没有任何区别。我是否需要以某种方式指出哪些列包含日期?
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-03-04
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多