【发布时间】:2012-03-05 14:39:44
【问题描述】:
我正在使用 JQuery tablesorter 插件。该表有一列以05 Mar 2012 格式显示日期。 tablesorter 插件似乎将此列视为文本,因为它按顺序对其进行排序
- 2012 年 3 月 5 日
- 2012 年 1 月 6 日
- 2012 年 12 月 7 日
如何改为按时间顺序对这些日期进行排序?
【问题讨论】:
标签: javascript jquery date tablesorter
我正在使用 JQuery tablesorter 插件。该表有一列以05 Mar 2012 格式显示日期。 tablesorter 插件似乎将此列视为文本,因为它按顺序对其进行排序
如何改为按时间顺序对这些日期进行排序?
【问题讨论】:
标签: javascript jquery date tablesorter
将日期字符串解析为日期,然后将其转换为毫秒。让 tablesorter 将列排序为数字。
$.tablesorter.addParser({
id: 'my_date_column',
is: function(s) {
// return false so this parser is not auto detected
return false;
},
format: function(s) {
var timeInMillis = new Date.parse(s);
return timeInMillis;
},
// set type, either numeric or text
type: 'numeric'
});
$(function() {
$("table").tablesorter({
headers: {
6: { // Change this to your column position
sorter:'my_date_column'
}
}
});
});
如果您在使用 Date.parse 时遇到问题,see my answer to this question。
【讨论】:
您还可以在日期之前以数字格式 (yyyymmdd) 添加隐藏的跨度标签。此文本将首先出现并用于排序,但它将隐藏在视线之外,仅显示您想要的格式。
<td><span style="display:none">20130923</span>23rd September 2013</td>
【讨论】:
您将需要使用 addParser 方法并创建一个解析器,将您的字符串转换为日期对象。
按照插件网站上的示例 http://tablesorter.com/docs/example-parsers.html
如果需要日期解析器:
编辑:您的日期可以轻松转换为所示格式:
console.log(new Date('05 Mar 2012'))// logs proper date object
【讨论】:
有一段时间没有使用 tablesorter,但我似乎记得在英国日期时遇到过类似的问题。
您可以使用自定义日期格式将 dateformat 参数添加到 tablesorter 插件。
dateFormat: 'dd MMM yyyy'
【讨论】: