Bootstrap表格:按日期字段排序

12
我正在使用这个Bootstrap表格插件。但是按日期排序无法正常工作。 这是代码:
<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)

我该如何修复它以便正确排序日期?


出于好奇,为什么你要使用PHP <?= 'expiry date' ?>来输出这个字符串?既然它是一个硬编码的字符串,为什么不直接在HTML中硬编码呢? - M. Eriksson
5个回答

9

您需要使用带有"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;
}

我遇到了这个错误:未捕获的类型错误:a.toDate 不是一个函数。 - netdev
我刚刚给了你一个例子,在这种情况下,toDate()是Moment.js的一个方法,用于将字符串转换为日期。 - PHPnoob
那么你更需要了解如何比较日期,而不是在 Bootstrap 表格中实现排序器。 - PHPnoob
2
@PHPnoob - 当你写回答时,除非确实必要,否则应避免添加额外的依赖项。如果你确实需要添加,你应该在回答中明确提到,否则对于问题提出者和未来的访问者来说,这将会更加混乱而不是有帮助的。 - M. Eriksson
我在这个小陷阱里被困住了。datesSorter函数必须附加到window,因为Bootstrap-table使用func = window[name];。然后它就完美地工作了。 - roland
显示剩余2条评论

8

<td>标签的开头加上将日期转换为数字的代码,如下所示

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


1
+1 这个答案简单易懂,而且无论你使用什么库或排序机制,它都能正常工作。它甚至可以根据你的需求进行调整。我使用了 ISO 日期字符串而不是 strtotime(),从而省去了时区的问题。 - Mark Roberts
工作得很棒。日期格式,例如德国的'd.m.Y',一点问题都没有。 - undefined

4

我使用一种简短的语法来调用函数,并使用'data-sorter'选项

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

2

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

然后根据您的需求进行调整:

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

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接