Bootstrap Table: 按日期字段排序

Bootstrap Table: sort by date field

我正在使用这个 Bootstrap table plugin。但是按日期排序不正常。

代码如下:

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

日期格式如下:d/m/y (17/7/14)

我该如何解决才能正确排序日期?

您必须使用具有 "data-sorter" 属性的自定义排序器,例如 data-sorter="datesSorter"

然后满足您的需求:

function datesSorter(a, b) {
  if (new Date(a) < new Date(b)) return 1;
  if (new Date(a) > new Date(b)) return -1;
  return 0;
}

我是这样工作的.... 我添加了一个新列(数字)并将其设置为隐藏。您可以通过将该日期转换为数字来轻松做到这一点。

$('#mainTable').bootstrapTable({
    sortStable: true,
    pagination: true,
    pageSize: 100,
    toolbar:"#toolbar",
    search: true,
    searchOnEnterKey: false,
    sortOrder: "desc",sortOrder: "desc",

    // here we determine the column that will sort the table
    sortName: "rel0",
    columns: [
        {
            // this is the hidden numeric column that works as sorter 
            field: 'rel0',
            title: 'rel0',                  
            visible:false,                             
        },
        {
            // this is the visible column
            field: 'rel',
            title: 'Date / hour',
        },
    ],
    data: objetoData
});

您必须使用带有“data-sorter”属性的自定义排序器,例如 data-sorter="datesSorter"。

然后满足您的需求:

function datesSorter(a, b) {
    return Date.parse(a) - Date.parse(b);
}

<td>内容开头日期转换成数字这样

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

我使用一个语法较短的函数,'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>