How to sort datatables with date in descending order

前端 未结 14 1882
我寻月下人不归
我寻月下人不归 2020-12-29 11:11

I wish to show the records using datatables with default ordering based on one of my rows with date & time in descending order. Please help me in editing the jquery stru

相关标签:
14条回答
  • 2020-12-29 11:48

    This questions is quite old and most of the plugins mentioned in the answers have either been deprecated or stopped working (I've tried all).

    Here is what works currently.

    Add an extension:

    $.fn.dataTable.ext.order['date-time'] = function (settings, col) {
        return this.api().column(col, { order: 'index' }).nodes().map(function (td, i) {
            var val = $(td).text().trim();    // Get datetime string from <td>
            return moment(val, "DD/MM/YYYY hh:mm:ss a").format("X"); 
        });
    }
    

    And then, for your data table:

    $('#example').DataTable({
        "columns": [
            null,
            null,
            null,
            { "orderDataType": "date-time" }, // date-time is a custom key created in the above ext
            null,
            null,
            null,
            null,
            null,
            null
         ]
    });
    

    Update: You can simplify the above using:

    $('#example').DataTable({
        "columnDefs": [
            { "orderDataType": "date-time", "targets": [3] }
        ]
    });
    

    The "targets": [] array can contain the indexes (from) of all the columns you want to apply the datetime sort to.

    Note: I have used moment.js, you can use any other method of creating a valid date/datetime object. Also, the reference used is for the dom-sort plugin, therefore, the same method can be used for sorting with columns with complex dom structures as well.

    Reference: https://datatables.net/examples/plug-ins/dom_sort

    0 讨论(0)
  • 2020-12-29 11:49

    I know this is an old thread. but you can basically use "aaSorting"

    $('#exemple').DataTable({
    
        "aaSorting": [[3,'desc']],
    });
    
    0 讨论(0)
提交回复
热议问题