How to sort datatables with date in descending order

前端 未结 14 1881
我寻月下人不归
我寻月下人不归 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:32

    Just add "type":"date" directly in the columns like { "data": "MyDateField", "type":"date" }.

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

    Try this, It works for me

    <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.8.4/moment.min.js"></script>
    <script src="https://cdn.datatables.net/plug-ins/1.10.21/sorting/datetime-moment.js"></script>
    <script>
        $(document).ready(function () {
            $.fn.dataTable.moment( 'DD/MM/YYYY HH:mm' );
            $('#example').DataTable({"order": [[ 3, "desc" ]]});
        });
    </script>
    
    0 讨论(0)
  • 2020-12-29 11:37

    Default sorting in Datatables:

    $(document).ready(function() { 
        $('#example').DataTable({ 
            "order": [[ 3, "desc" ]] 
        }); 
    });
    

    You can use asc for ascending order. And 3 means, 4th column is going to be ordered default.

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

    I got the solution with the sorting of date. Just add type as 'date' and in targets, you have pass column number(count start from 0) with datatable options. And set 'order' with column number and type of format. See below code,

    columnDefs: [ { type: 'date', 'targets': [4] } ],
    order: [[ 4, 'desc' ]]
    
    0 讨论(0)
  • 2020-12-29 11:41

    Perfect solution that I could implement is this:

    1. If you generate data with AJAX at PHP file just make the line with date this way:
    $rows[] =
        [
        "name" => $name,
        "date" => [
            "display" => $date, // Ex: '31.12.2020'
            "timestamp" => strtotime($date),    // Timestamp value for ordering, Ex: 1609372800
        ]
    ]
    
    1. Then row would be output to JSON like this:
    {
    "name": "Vasya Pupkin",
    "date": {
            "display": "31.12.2020",
            "timestamp": "1609372800"
        },
    }
    
    1. Finish by editing your JavaScript TadaTables object "date" column like this:
    {
        "data": "date",
        render: {
            _: 'display',
            sort: 'timestamp'
        }
    },
    
    1. That's all! Now column with date is perfectly sorted.
    0 讨论(0)
  • 2020-12-29 11:46

    The simpliest way is to add a hidden timestamp before the date in every TD tag of the column, for example:

    <td class="sorting_1">
        <span style="display:none;">1547022615</span>09/01/2019  09:30
    </td>
    

    With the default string ordering, a timestamp would order the column the way you want and it will not be shown when rendered in the browser.

    0 讨论(0)
提交回复
热议问题