Bootstrap Table: sort by date field
12,762
Solution 1
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;
}
Solution 2
Put at the begining of <td>
content the date translate to number like this
<span style="display:none">{{strtotime($date)}}</span>
Solution 3
I use a function with a short syntax, with the 'data-sorter' option:
<table
id="table"
data-toggle="table"
data-height="460"
data-url="json/data1.json">
<thead>
<tr>
<th data-field="id">ID</th>
<th data-field="name">Item Name</th>
<th data-field="date" data-sortable="true" data-sorter="dateSorter">Item Date</th>
</tr>
</thead>
</table>
<script>
function dateSorter(a, b){
return(new Date(a).getTime() - new Date(b).getTime());
}
</script>
Solution 4
You must use a custom sorter with "data-sorter" attribute like data-sorter="datesSorter".
Then to fit your needs:
function datesSorter(a, b) {
return Date.parse(a) - Date.parse(b);
}
Author by
netdev
Updated on June 05, 2022Comments
-
netdev almost 2 years
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?
-
netdev about 5 yearsI get this error: Uncaught TypeError: a.toDate is not a function
-
PHPnoob about 5 yearsI just gave you an example, in this case toDate() refers to a Moment.js method that converts a string to a date.
-
PHPnoob about 5 yearsThen you're more looking for how to compare dates than implement a sorter in bootstrap table.
-
M. Eriksson about 5 years@PHPnoob - When writing an answer, you should refrain from adding extra dependencies unless it's really necessary. And if you do, you should definitely mention that in your answer, or it will be more confusing than helpful for the OP and future visitors.
-
PHPnoob about 5 years@MagnusEriksson I specified it was an example to give him the way to do, which i thought was clear enough to be understood. I just edited my answer anyway.
-
M. Eriksson about 5 yearsNever assume anything :-) It's important to be extra explicit when writing answers.
-
roland over 4 yearsI was trapped in a little pitfall with this. The
datesSorter
function must be attached towindow
since Bootstrap-table usesfunc = window[name];
. Then it works perfectly.