【问题标题】:Date With Timestamp Sorting Issue in JQuery DatatablesJQuery数据表中带有时间戳排序问题的日期
【发布时间】:2017-07-22 15:39:58
【问题描述】:

我正在使用 jquery 数据表插件来列出我的 java spring MVC Web 应用程序中的数据。表中的一个字段包含带有时间戳的日期。在那,我一直在尝试对数据元素进行排序。当我尝试使用时间戳对包含日期的字段中的元素进行排序时,排序不起作用。

我正在使用以下 jquery 进行数据表初始化

 $('.swcm-dt-basic').dataTable( {
        "responsive": true,
        "order": \[\],
        "language": {
            "paginate": {
              "previous": '<i class="swcm-psi-arrow-left"></i>',
              "next": '<i class="swcm-psi-arrow-right"></i>'
            }
        }
    } );

下图显示了问题

【问题讨论】:

    标签: javascript jquery datatables


    【解决方案1】:

    解决方案 1

    对包含可排序时间戳的td 元素使用data-order 属性。例如:

    <td data-order="2016-12-02 21:28:41">12/02/2016 21:28:41</td>
    

    有关代码和演示,请参阅this example

    解决方案 2

    使用sorting plugins 就像datetime-moment 用于任何日期格式或date-euro 如果您的日期是DD/MM/YYYY HH:MM:SS 格式。

    如果您的日期在MM/DD/YYYY HH:MM:SS,您可以使用以下代码:

    jQuery.extend( jQuery.fn.dataTableExt.oSort, {
        "date-us-pre": function ( a ) {
            var x;
     
            if ( $.trim(a) !== '' ) {
                var frDatea = $.trim(a).split(' ');
                var frTimea = (undefined != frDatea[1]) ? frDatea[1].split(':') : [00,00,00];
                var frDatea2 = frDatea[0].split('/');
                x = (frDatea2[2] + frDatea2[0] + frDatea2[1] + frTimea[0] + frTimea[1] + frTimea[2]) * 1;
            }
            else {
                x = Infinity;
            }
    
            return x;
        },
     
        "date-us-asc": function ( a, b ) {
            return a - b;
        },
     
        "date-us-desc": function ( a, b ) {
            return b - a;
        }
    } );
    
    $(document).ready(function(){
       $('#example').dataTable( {
          columnDefs: [
             { type: 'date-us', targets: 0 }
          ]
       } );
    }
    

    【讨论】:

      【解决方案2】:

      如果您只是在寻找一个简单的解决方案来对该列进行排序,我不确定您的问题,请使用 yyyymmdd hh:mm:ss 格式。 但是,如果您特别关注 mm/dd/yyyy hh:mm:ss 格式,请尝试以下建议: https://stackoverflow.com/a/25359251/3483409 https://stackoverflow.com/a/33568433/3483409

      【讨论】:

        【解决方案3】:

        你可以使用这样的东西。

        $('#example').dataTable( {
             columnDefs: [
               { type: 'de_datetime', targets: 0 },
               { type: 'de_date', targets: 1 }
             ]
          } );
        

        欲了解更多信息,您可以访问https://datatables.net/plug-ins/sorting/date-de

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2020-05-23
          • 2018-07-08
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2016-12-11
          • 2015-03-03
          相关资源
          最近更新 更多