-1

is it possible to sort a datatables table by date ascending?

This is my current table ->

current table

I want it to be sorted like a calender in an ascending order, something like the following:

22.01
22.01
...
23.01
...
31.01
01.02

 $(document).ready(function () {
        $('#example').DataTable({
            searching: false,
            paging: false,
            bInfo: false,
            order: [[3, "asc"], [2, "asc"], [1, "asc"]],
            columnDefs: [
                {
                    targets: 3,
                    type: 'date',
                    className: 'mdl-data-table__cell--non-numeric'
                }
            ]
        });
    });

This is what I am using right now, i tried type: date-eu as well.

Thanks in advance!

Update:

I went with something like that, https://datatables.net/plug-ins/sorting/datetime-moment, works fine.

Appreciate the help

benl96
  • 274
  • 3
  • 18
  • I have created one [jsfiddle](https://jsfiddle.net/Jaydeep_Mor/ca59wd1m/13/) for you [#Resource](https://stackoverflow.com/a/25405903/6656706). Hopefully work for you. Tell me if anything wrong. – Jaydeep Mor Jan 21 '20 at 08:20

2 Answers2

0

Before trying the following your dates should be formatted as MM DD YYYY. Try this:`

let dates = ["01.22.2020", "01.18.2020", "02.02.2020"];
let datesFormatted = [];

dates.forEach(i => {datesFormatted.push(new Date(i))});

datesFormatted.sort(function(a, b) {
  if (a > b) {
    return 1;
  } else {
    return -1;
  }
});

console.info(datesFormatted);

`

Super Hornet
  • 2,839
  • 5
  • 27
  • 55
0

If you can get your date in ISO yyyy-mm-dd format you can make use of the HTML5 data-order attribute. Add it to your cell using createdCell inside your columnDefs.

  'columnDefs': [
     {
        'targets': 3,
        'createdCell':  function (td, cellData, rowData, row, col) {
           $(td).attr('data-order', row.isodate);
        }
     }
  ]
mark_b
  • 1,393
  • 10
  • 18