简体   繁体   中英

How to make custom date sort in datatables?

I have table with column of dates:

2015-03-03 20:14 
2015-04-15 20:33 
2015-04-20 09:34 
2015-04-28 22:18

But some cells have no date (I mark it - ). When I am using the general sorting function it looks like:

—
—
—
2015-03-03 20:14
2015-04-15 20:33
2015-04-20 09:34
2015-04-28 22:18

but I need:

2015-03-03 20:14
2015-04-15 20:33
2015-04-20 09:34
2015-04-28 22:18
— 
—
—

Actually, I had to sort by two parameters and also set rows without date in the end of table. I added two data attribute (status and date in timestamp format):

<tr>
  <td><span class="label label-warning" data-status="0" data-date="1397562467">Status 0</span></td>
  <td>2015-03-03 20:14</td>
</tr>
<tr>
  <td><span class="label label-warning" data-status="1" data-date="1397567321">Status 1</span></td>
  <td>2015-04-15 20:33</td>
</tr>
<tr>
  <td><span class="label label-warning" data-status="0" data-date="1397567746">Status 0</span></td>
  <td>2015-04-20 09:34</td>
</tr>
<tr>
  <td><span class="label label-warning" data-status="0" data-date="1397567321">Status 0</span></td>
  <td>2015-04-15 20:33</td>
</tr>

I made new custom sort function:

jQuery.fn.dataTableExt.oSort['status-date-asc']  = function(x,y) {

                var xStatus, xDate, yStatus, yDate;

                xStatus = $(x).data('status');
                yStatus = $(y).data('status');
                xDate   = $(x).data('date');
                yDate   = $(y).data('date');

                return xStatus > yStatus ? 1
                        : xStatus < yStatus ? -1
                        : xDate > yDate ? 1
                        : xDate < yDate ? -1 : 0;

            };

And init this row with new sort function:

        var currentTable = $('#current_table').dataTable( {

            "aaSorting": [ [5, 'asc'] ],
            "aoColumns": [
                null,
                null,
                null,
                null,
                null,
                { "sType": 'status-date' },
                null,
                null,
                null
            ],
      });

Finally, it looks:

  • status 0, date = 2015-03-03 20:14
  • status 0, date = 2015-04-15 20:33
  • status 0, date = 2015-04-20 09:34
  • status 0, date = 2015-04-28 22:18
  • status 0, date = n/a
  • status 0, date = n/a
  • status 0, date = n/a
  • status 1, date = 2015-03-03 20:14
  • status 1, date = 2015-04-15 20:33
  • status 1, date = 2015-04-20 09:34
  • status 1, date = 2015-04-28 22:18
  • status 1, date = n/a
  • status 1, date = n/a
  • status 1, date = n/a

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM