Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bootstrap Table: sort by date field

I am using this Bootstrap table plugin. But sorting by date is not working properly.

Here is the code:

<table class=" table-striped" id="table" data-toggle="table"
    data-search="true"
    data-filter-control="true"
    data-click-to-select="true"
    data-escape="false">

    <thead>
        <tr>
            <th data-field="expiry_date" data-sortable="true" scope="col"><?= 'expiry date' ?></th>
        </tr>
    </thead>

Date is in this format: d/m/y (17/7/14)

How I can fix it in order to sort dates properly?

like image 268
netdev Avatar asked Mar 14 '19 14:03

netdev


People also ask

How do I sort data in bootstrap table?

The sort table needed a bootstrap table with a JavaScript method. There is two ways to sort table data which is below. The first way helps to sort table data automatically using the DataTable() method. The second way helps the user to sort table data as per requirement.

How do I make a table sortable in HTML?

Adding the "sortable" class to a <table> element provides support for sorting by column value. Clicking the column headers will sort the table rows by that column's value. Tables must use <thead> and <th> tags for sortable functionality to work. The <th> tag defines a header cell in an HTML table.


2 Answers

You must use a custom sorter with "data-sorter" attribute like data-sorter="datesSorter"

Then to fit your needs :

function datesSorter(a, b) {
  if (new Date(a) < new Date(b)) return 1;
  if (new Date(a) > new Date(b)) return -1;
  return 0;
}
like image 60
PHPnoob Avatar answered Oct 14 '22 00:10

PHPnoob


Put at the begining of <td> content the date translate to number like this

<span style="display:none">{{strtotime($date)}}</span>

like image 39
Diego Gandino Avatar answered Oct 14 '22 00:10

Diego Gandino