【问题标题】:DataTables: Date Sorting not working on Firefox & IEDataTables:日期排序在 Firefox 和 IE 上不起作用
【发布时间】:2013-11-04 13:49:37
【问题描述】:

我在这 2 个浏览器中对日期列的排序有问题,在 chrome 中它可以正常工作。

我现在不知道会发生什么,希望有人可以帮助我。

我使用的格式是(月份名称年份)Ex> 2013 年 10 月

代码:(包含日期的列是数字2)

   <script type="text/javascript" charset="utf-8">
$(document).ready(function() {
    $('#resultados').dataTable( {
        "sPaginationType": "full_numbers",
aaSorting: [] ,
        "aoColumnDefs": [
          { 'bSortable': false, 'aTargets': [ 1,4 ] },

       ],
        "aLengthMenu": [[25, 50, 75, 100], [25, 50, 75, 100]],
        "iDisplayLength": 100
    } );
} );

</script>

提前致谢。

【问题讨论】:

    标签: sorting date datatables


    【解决方案1】:

    不确定 FF,但旧的 IE 可能会在冗余 , 的情况下失败

    所以试试下面的代码:

    $(document).ready(function () {
        $('#resultados').dataTable({
            "sPaginationType": "full_numbers",
            aaSorting: [],
            "aoColumnDefs": [
                { 'bSortable': false, 'aTargets': [ 1, 4 ] }
            ],
            "aLengthMenu": [[25, 50, 75, 100], [25, 50, 75, 100]],
            "iDisplayLength": 100
        });
    });
    

    jslint 是否删除了多余的,(在[ 1,4 ] } 之后)

    【讨论】:

    • 感谢丹尼尔的回复,很遗憾没有成功。我在 3 个浏览器中进行了测试,并且只在 chrome 中继续工作
    • @user2952715,看看 FF firebug 或 IE 开发工具
    【解决方案2】:

    原来 IE 和 FF 上的 Date.parse() 实现不能正确解释这些字符串,但 chrome 可以!

    我创建了一个插件来让它工作(注意——我已经在 github 上放了一个 pull request 以便将来将它放入主仓库):

    /**
     * This sorting plug-in will sort, in calendar order, data which
     * is in the format "MMMM yyyy". Inspired by forum discussion:
     * http://datatables.net/forums/discussion/1242/sorting-dates-with-only-month-and-year
     *
     *  @name Date (MMMM yyyy)
     *  @anchor Sort dates in the format `MMMM yyyy`
     *  @author Phil Hurwitz
     *
     *  @example
     *    $('#example').dataTable( {
     *       columnDefs: [
     *         { type: 'stringMonthYear', targets: 0 }
     *       ]
     *    } );
     */
    
    jQuery.extend(jQuery.fn.dataTableExt.oSort, {
        "stringMonthYear-pre": function (s) {
            var months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
    
            var dateComponents = s.split(" ");
            dateComponents[0] = dateComponents[0].replace(",", "");
            dateComponents[1] = jQuery.trim(dateComponents[1]);
    
            var year = dateComponents[1];
    
            var month = 0;
            for (var i = 0; i < months.length; i++) {
                if (months[i].toLowerCase() == dateComponents[0].toLowerCase()) {
                    month = i;
                    break;
                }
            }
    
            return new Date(year, month, 1);
        },
    
        "stringMonthYear-asc": function (a, b) {
            return ((a < b) ? -1 : ((a > b) ? 1 : 0));
        },
    
        "stringMonthYear-desc": function (a, b) {
            return ((a < b) ? 1 : ((a > b) ? -1 : 0));
        }
    });
    

    【讨论】:

      【解决方案3】:
          Data table support by default "YYYY-MM-DD" so to support date format "dd-MMM-yyyy" and "MMM-yyyy" we need to include a plugin code below:-
      
              (function () {
      
              var customDateDDMMMYYYYToOrd = function (date) {
                  "use strict"; //let's avoid tom-foolery in this function
                  // Convert to a number YYYYMMDD which we can use to order
                  var dateParts = date.split(/-/);
                  return (dateParts[2] * 10000) + ($.inArray(dateParts[1].toUpperCase(), ["JAN", "FEB", "MAR", "APR", "MAY", "JUN", "JUL", "AUG", "SEP", "OCT", "NOV", "DEC"]) * 100) + (dateParts[0]*1);
              };
      
              // This will help DataTables magic detect the "dd-MMM-yyyy" format; Unshift
              // so that it's the first data type (so it takes priority over existing)
              jQuery.fn.dataTableExt.aTypes.unshift(
                  function (sData) {
                      "use strict"; //let's avoid tom-foolery in this function
                      if (/^([0-2]?\d|3[0-1])-(jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)-\d{4}/i.test(sData)) {
                          return 'date-dd-mmm-yyyy';
                      }
                      return null;
                  }
              );
      
              // define the sorts
              jQuery.fn.dataTableExt.oSort['date-dd-mmm-yyyy-asc'] = function (a, b) {
                  "use strict"; //let's avoid tom-foolery in this function
                  var ordA = customDateDDMMMYYYYToOrd(a),
                      ordB = customDateDDMMMYYYYToOrd(b);
                  return (ordA < ordB) ? -1 : ((ordA > ordB) ? 1 : 0);
              };
      
              jQuery.fn.dataTableExt.oSort['date-dd-mmm-yyyy-desc'] = function (a, b) {
                  "use strict"; //let's avoid tom-foolery in this function
                  var ordA = customDateDDMMMYYYYToOrd(a),
                      ordB = customDateDDMMMYYYYToOrd(b);
                  return (ordA < ordB) ? 1 : ((ordA > ordB) ? -1 : 0);
              };
      
              })();
      
              and we have to specify the new introduced type to column of date as below:-
              var costRevenueGraph = $('#costRevenueGraphTbl').dataTable({
                                      "sPaginationType": "full_numbers",
                                      "paging": true,
                                      "bSort": true,
                                      "ordering": false,
                                      "info": false,
                                      "iDisplayLength": 10,
                                      "aaData": costRevenueGraphData,
                                      "sImgDirPath": "http://assets.cms.gov/resources/libs/datatables/1.9.1/images/",
                                      "aoColumns": [
                                          { "mDataProp": "day","sType":'date-dd-mmm-yyyy' },
                                          { "mDataProp": 'cost',"sType":'formatted-num' },
                                          { "mDataProp": 'costOFInternalFailure',"sType":'formatted-num' },
                                          { "mDataProp": 'costOFExternalFailure',"sType":'formatted-num' },
                                          { "mDataProp": 'costOFPreventiveInvestment',"sType":'formatted-num' },
                                          { "mDataProp": 'costOFAssessmentInvestment',"sType":'formatted-num' },
                                          { "mDataProp": 'costOfRedHerringInvestment',"sType":'formatted-num' },
                                          { "mDataProp": 'revenue',"sType":'formatted-num' }
                                      ],
                                      "aoColumnDefs": [{
                                          "aTargets": [0],
                                          "fnRender": function(data, type, row) {
                                              return $filter('date')(data.aData[data.mDataProp], 'dd-MMM-yyyy');
                                          }
                                      },{
                                          "aTargets": [1,2,3,4,5,6,7],
                                          "aType":'formatted-num',
                                          "fnRender": function(data, type, row) {
                                              return $filter('currency')(data.aData[data.mDataProp], '$');
                                          }
                                      }]
                                  });
          As same above if we want to support format "MMM-yyyy" we need to do a little hack
          (function () {
      
          var customDateDDMMMYYYYToOrd = function (date) {
              "use strict"; //let's avoid tom-foolery in this function
              // Convert to a number YYYYMMDD which we can use to order
              date= "01-"+date
              var dateParts = date.split(/-/);
              return (dateParts[2] * 10000) + ($.inArray(dateParts[1].toUpperCase(), ["JAN", "FEB", "MAR", "APR", "MAY", "JUN", "JUL", "AUG", "SEP", "OCT", "NOV", "DEC"]) * 100) + (dateParts[0]*1);
          };
      
          // This will help DataTables magic detect the "dd-MMM-yyyy" format; Unshift
          // so that it's the first data type (so it takes priority over existing)
          jQuery.fn.dataTableExt.aTypes.unshift(
              function (sData) {
                  sData= "01-"+date
                  "use strict"; //let's avoid tom-foolery in this function
                  if (/^([0-2]?\d|3[0-1])-(jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)-\d{4}/i.test(sData)) {
                      return 'date-dd-mmm-yyyy';
                  }
                  return null;
              }
          );
      
          // define the sorts
          jQuery.fn.dataTableExt.oSort['date-dd-mmm-yyyy-asc'] = function (a, b) {
              "use strict"; //let's avoid tom-foolery in this function
              var ordA = customDateDDMMMYYYYToOrd(a),
                  ordB = customDateDDMMMYYYYToOrd(b);
              return (ordA < ordB) ? -1 : ((ordA > ordB) ? 1 : 0);
          };
      
          jQuery.fn.dataTableExt.oSort['date-dd-mmm-yyyy-desc'] = function (a, b) {
              "use strict"; //let's avoid tom-foolery in this function
              var ordA = customDateDDMMMYYYYToOrd(a),
                  ordB = customDateDDMMMYYYYToOrd(b);
              return (ordA < ordB) ? 1 : ((ordA > ordB) ? -1 : 0);
          };
      
          })();
      
      and how to implement here is a demo
      var costRevenueGraph = $('#fcSimulationGraphTbl').dataTable({
                              "sPaginationType": "full_numbers",
                              "paging": true,
                              "bSort": true,
                              "ordering": false,
                              "info": false,
                              "iDisplayLength": 10,
                              "aaData": forecastingGraphObjTblData,
                              "sImgDirPath": "http://assets.cms.gov/resources/libs/datatables/1.9.1/images/",
                              "aoColumns": [
                                  { "mDataProp": "day","sType":'date-dd-mmm-yyyy' },
                                  { "mDataProp": 'forecastDemand',"sType":'formatted-num' },
                                  { "mDataProp": 'actualDemand',"sType":'formatted-num' },
                                  { "mDataProp": 'actualAbsolutePercentageError',"sType":'percent' },
                                  { "mDataProp": 'trackingSignal',"sType":'percent' }
                              ],
                              "aoColumnDefs": [{
                                  "aTargets": [0],
                                  "fnRender": function(data, type, row) {
                                      return $filter('date')(data.aData[data.mDataProp], 'MMM-yyyy');
                                  }
                              },{
                                  "aTargets": [1,2],
                                  "aType":'formatted-num',
                                  "fnRender": function(data, type, row) {
                                      return $filter('number')(data.aData[data.mDataProp]);
                                  }
                              },{
                                  "aTargets": [3,4],
                                  "aType":'percent',
                                  "fnRender": function(data, type, row) {
                                      return data.aData[data.mDataProp]+'%';
                                  }
                              }]
                          });
      

      【讨论】:

        【解决方案4】:

        我也遇到了同样的问题,我已经通过使用以下技巧解决了它:

        <span style="display: none;">{{ date('Y-m-d', strtotime($date_varilable)) }}</span>
        

        我已经放置了相同的span 标签,该标签是隐藏的,但日期为'Y-m-d' 格式,ChromeFirefox 正确解析了这种格式,并且工作正常。

        解释: 此技巧用于在有复选框的列上提供排序,并且它的选中或未选中基于某个值。在这种情况下,跨度值用于数据表库的排序目的。

        【讨论】:

          猜你喜欢
          • 2016-03-25
          • 1970-01-01
          • 2012-03-24
          • 1970-01-01
          • 2013-07-23
          • 2012-11-04
          • 2014-02-28
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多