25

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 structure for that

enter image description here

3
  • 4
    and where's the jQuery structure you want us to help editing?
    – Jeff
    Commented Jun 14, 2016 at 14:01
  • btw, as far as I know on date and time sorting there should be some limitations in how datatable handles the sorting process Commented Jun 14, 2016 at 14:02
  • I have done it in my project. date format should be YYYY-MM-DD. sort it *"order": [[ 3, "desc" ]] * and hide the td, th display none.
    – ThataL
    Commented Mar 4, 2019 at 10:56

18 Answers 18

33

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.

5
  • Hi Joan, I tried this method, but it doesn't work. It assumed 1547022615 as a string instead of a number. Any idea?
    – Sam
    Commented Jul 23, 2019 at 4:05
  • 1
    For extreme cases, you'd just need to left pad it with zeros to allow the unix string to be compared properly, right, @Sam? Commented Aug 1, 2020 at 5:37
  • @mickmackusa great idea. padding with zero should work. the only caveat is to have a predetermine length (ie. size of the string), but it could work. Thanks for sharing!
    – Sam
    Commented Aug 1, 2020 at 8:13
  • 1
    Thanks a lot, it works perfectly, cheers! Commented Jan 20, 2021 at 1:44
  • 2
    Instead of adding a new field, in the existing date field add this: <td data-sort="@item.Created.ToString("yyyyMMddHHmmssffff")">
    – mchar
    Commented May 6, 2021 at 14:45
21

I had same problem. I used date-eu sorting plugin to sort dates in the format DD/MM/YY and I included the following JS file :

<script src="//cdn.datatables.net/plug-ins/1.10.11/sorting/date-eu.js" type="text/javascript"></script>

This worked for me.

$('#exemple').DataTable({
    "order": [[ 3, "desc" ]], //or asc 
    "columnDefs" : [{"targets":3, "type":"date-eu"}],
});

Read also this post on stackoverflow: Sorting date in datatable

0
20

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' ]]
2
  • 1
    you can also use it directly in the columns. columns: [ { "data": "MyDateField", "type":"date" } ]
    – jplara
    Commented Oct 30, 2019 at 21:12
  • Can you define your date format using this solution? E.g. 'dd-mm-yyyy'.
    – mark_b
    Commented Sep 29, 2021 at 14:05
9

Please refer to this pen: https://codepen.io/arnulfolg/pen/MebVgx

It uses //cdnjs.cloudflare.com/ajax/libs/moment.js/2.8.4/moment.min.js and //cdn.datatables.net/plug-ins/1.10.12/sorting/datetime-moment.js for sorting datatable

To sort the table by default use:

$.fn.dataTable.moment('DD/MM/YY');
$('#example').DataTable({ 
       "order": [[ 3, "desc" ]] 
    }); 
8

You can order by adding a dataset attribute in the record. Click here for details.

Example:

<td data-search="21st November 2016 21/11/2016" data-order="1479686400">
    21st November 2016
</td>

To show data sorted from the initial state define a column to look for sorting. For example:

$('#dataTable').DataTable({
    "order": [[10, 'desc']],
});
1
  • 1
    This works very well for me. I don't need to add any scripts or custom scripts (eg. moment.js) for the 'data-order', I just generate a 'yyyyMMdd' value. eg. @row.DateValue.ToString('yyyyMMdd') and it works perfectly Commented Sep 27, 2022 at 12:05
6

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

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

Format your date in yyyyMMddHHmm. This will be your sortable timestamp. Then hide the formatted date using display none. This is actually a further explanation of the answer of joan16v

0
5

//working here code

$('#table').DataTable({
   columnDefs: [ { type: 'date', 'targets': [3] } ],
   order: [[ 3, 'desc' ]],          
});
0
4

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

$('#exemple').DataTable({

    "aaSorting": [[3,'desc']],
});
1
  • 1
    Or order: [[ 3, 'desc' ]] since DataTables v1.10 .
    – S. Esteves
    Commented Oct 30, 2019 at 6:25
4

This was the answer for me:

<td data-order=<fmt:formatDate pattern = "yyyy-MM-dd" value = "${myObject.myDate}" />>${myObject.myDate}</td>

more details, here in the html5 section: https://datatables.net/manual/data/

1
  • 1
    I also used this, the solution is to set the datetime string to yyyy-MM-dd in data-order. Thanks!
    – Emmie
    Commented Apr 9, 2020 at 14:18
2

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
2

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

1

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>
1

This worked for me. Don't forget to add moment to your code. I'm using node, so here is my import.

npm i moment -S

import moment from 'moment';

$('#example').DataTable({
    "order": [[ 3, "desc" ]], //or asc 
    "columnDefs" : [
       {
          targets: [3],
          render: function (data, type) {
             if (data !== null) {
                var wrapper = moment(new Date(data));
                return wrapper.format("MM/DD/YYYY h:mm:ss A");
             }
          }
       }
    ],
});

All credit to Ryan Besko. Answer found here: https://forums.asp.net/t/2154454.aspx?DataTables+Date+Time+sorting+DD+MM+YYYY+HH+mm+a

1
  • Just be aware that Moment.js is now a legacy project and is no longer receiving updates.
    – mark_b
    Commented Sep 29, 2021 at 13:59
0
            Here the code:


           jQuery.extend(jQuery.fn.dataTableExt.oSort, {
             "date-uk-pre": function ( a ) {
              var ukDatea = a.split('-');
              return (ukDatea[2] + ukDatea[1] + ukDatea[0]) * 1;
           },


            "date-uk-asc": function ( a, b ) {
                return ((a < b) ? -1 : ((a > b) ? 1 : 0));
             },

            "date-uk-desc": function ( a, b ) {
               return ((a < b) ? 1 : ((a > b) ? -1 : 0));
              }
            }); 
0

As mentioned before date-eu.js library will work but for me it nedded a modification in the code:

jQuery.extend( jQuery.fn.dataTableExt.oSort, {
"date-eu-pre": function ( date ) {
    date = date.replace(" ", "");

    if ( !date ) {
        return 0;
    }

    var year;
    var eu_date = date.split(/[\.\-\/]/);


    if((eu_date[0] == undefined) || (eu_date[1] == undefined) || (eu_date[2] == undefined) ){
        eu_date[0] = 0;
        eu_date[1] = 0;
        eu_date[2] = 0;
    }

    //console.log(eu_date);

    /*year (optional)*/
    if ( eu_date[2] ) {
        year = eu_date[2];
    }
    else {
        year = 0;
    }

    /*month*/
    var month = eu_date[1];
    if ( month.length == 1 ) {
        month = 0+month;
    }

    /*day*/
    var day = eu_date[0];
    if ( day.length == 1 ) {
        day = 0+day;
    }

    return (year + month + day) * 1;
},

"date-eu-asc": function ( a, b ) {
    return ((a < b) ? -1 : ((a > b) ? 1 : 0));
},

"date-eu-desc": function ( a, b ) {
    return ((a < b) ? 1 : ((a > b) ? -1 : 0));
}

} );

0

This worked for me:

let options = {
  order: [[0, 'des']],
  columnDefs : [{"type":"date", "targets": 0}],
  ...
}
-1

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.

1
  • 7
    I used this. It is working for normal data. It was not working for date
    – Sujitha M
    Commented Jun 15, 2016 at 3:41

Not the answer you're looking for? Browse other questions tagged or ask your own question.