Bootstrap Table: sort by date field

netdev picture netdev · Mar 14, 2019 · Viewed 9k times · Source

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?

Answer

PHPnoob picture PHPnoob · Mar 14, 2019

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;
}