使用tablesorter对日期字段进行排序

我正在使用JQuery tablesorter插件。 该表格的列以05 Mar 2012的格式显示日期。 tablesorter插件似乎将此列视为文本,因为它按顺序对其进行排序

  • 2012年3月5日
  • 2012年1月6日
  • 2012年12月7日

我怎样才能按时间顺序对这些日期进行排序?

将日期字符串解析为Date,然后将其转换为毫秒。 让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时遇到问题, 请参阅我对此问题的回答 。

您还可以在日期之前以数字格式(yyyymmdd)添加隐藏的span标记。 此文本将首先出现并用于排序,但它将隐藏在视线之外,仅显示您想要的格式。

  2013092323rd September 2013 

您将需要使用addParser方法并创建一个将字符串转换为日期对象的解析器。

按照插件网站http://tablesorter.com/docs/example-parsers.html上的示例进行操作

如果需要日期解析器:

http://www.datejs.com/

编辑:您的日期很容易转换为显示的格式:

  console.log(new Date('05 Mar 2012'))// logs proper date object 

有一段时间没有使用过tableorter但我似乎记得在英国约会时有类似的问题。

您可以使用自定义日期格式向dateorter插件添加dateformat参数。

 dateFormat: 'dd MMM yyyy'