【问题标题】:Jquery datatables date sortingJquery数据表日期排序
【发布时间】:2016-12-11 15:39:34
【问题描述】:

我正在使用 jQuery DataTables,尝试对具有 2 种不同日期类型的数据列进行排序。

我有 2 种不同的格式月/年和日/月/年,但它们的排序不正确。

当前代码:

 function dateSorter(a, b) {
    var datea = a.split("/");
    var dateb = b.split("/");

    if (datea[1] > dateb[1]) return 1;
    if (datea[1] < dateb[1]) return -1;
  if (datea[0] > dateb[0]) return 1;
    if (datea[0] < dateb[0]) return -1;
    if( datea.length == 2 )
    {
    if (datea[2] > dateb[2]) return 1;
    if (datea[2] < dateb[2]) return -1;
    }
    else
    {
    if( datea[1] > dateb[2] ) return 1;
    if( datea[2] < dateb[1] ) return -1;
    }
    return 0;
}

以上是当前代码,它适用于月/年格式并对其进行很好的排序,但不能与两种格式混合。

这目前从日/月/年格式中对日/月进行排序,但不能正确地对年进行排序。

示例(当前):

03/04/2016
12/04/2017
12/05/2015
01/2015
02/2015
02/2016
01/2018
...

应该是:

01/2015
02/2015
12/05/2015
02/2016
03/04/2016
12/04/2017
01/2018

【问题讨论】:

    标签: sorting date datatables


    【解决方案1】:
    $.extend( jQuery.fn.dataTableExt.oSort, {
        "date-time-odd-pre": function (a){
            if(/\d{1,2}\/\d{1,2}\/\d{4}/.test(a)){
                return parseInt(moment(a, "DD/MM/YYYY").format("X"), 10);
            }else{
                return parseInt(moment(a, "MM/YYYY").format("X"), 10);
            }
        },
        "date-time-odd-asc": function (a, b) {
            return a - b;
        },
        "date-time-odd-desc": function (a, b) {
            return b - a;
        }
    });
    

    应该work,尽管您需要有空。

    希望对您有所帮助。

    【讨论】:

    • +1,相信这会起作用,但这也是基于对自定义排序插件的典型误解:-pre -asc-desc 函数没有多大意义。要么您有一个 -pre 函数,该函数将固定值传递给 dataTables 自动检测的基于类型的排序,您有 -asc-desc 方法来完成所有工作。你不能两者兼得。试试代码,我确信date-time-odd-ascdate-time-odd-desc 根本不会执行。我自己也有过这种误解,很多老插件也有这种冗余。
    猜你喜欢
    • 2015-03-03
    • 1970-01-01
    • 1970-01-01
    • 2018-11-22
    • 2015-02-06
    • 1970-01-01
    • 2020-06-20
    • 2011-09-09
    相关资源
    最近更新 更多