如何在javascript中按时间(格式:下午5:40)排序以与DataTables一起使用?

我有一个我正在使用的数据表有5列( http://datatables.net/ )

列是

  1. 日期格式:1月5日
  2. 时间格式:上午10:31(xx:xx XX)
  3. 第3,4,5列并不重要,它们只是我不关心排序的数据,只要1和2是正确的。

我想按Date FIRST排序(最近一次),然后我想按时间排序(最近一次排在最前面)。

因此1月5日下午4:58应该在凌晨4:58之前显示,显然所有其他数字也需要在其他所有时间都能正常工作。 格式始终相同,即:上午12:34,下午4:15,上午12:00等。

对于约会,这已经完美无缺。 数据表中只有2天的数据最大值,所以即使它翻到本月的第1天,它仍会显示在顶部,这很好。 我查看了文档,我很困惑如何为我的时间列做正确的排序。

这是我的代码:

oTable = $('#posts').dataTable({ "bSort": true, "aaSorting": [ [0,'desc'], [1,'asc'] ], "aoColumns": [ null, { "sType": 'time-sort' }, null, null, null ] }); 

这是从这里: http : //datatables.net/release-datatables/examples/basic_init/multi_col_sort.html

我现在采取它我必须使用“aoColumns”的sType属性为时间构建某种自定义排序算法(您可以在上面的示例链接中看到它区分大小写的情况),我不知道如何执行此操作:(我甚至不确定我到目前为止是否做到了这一点。它似乎对两列很好,但现在我需要做到这一点,所以时间是正确的…

这是我认为我需要的代码的另一部分。 (再一次,这是来自这个例子)。 我99%确定这是我需要在我的自定义时间排序代码中进行升序和降序的地方。

 /* Define two custom functions (asc and desc) for time sorting */ jQuery.fn.dataTableExt.oSort['time-sort-asc'] = function(x,y) { return ???; }; jQuery.fn.dataTableExt.oSort['time-sort-desc'] = function(x,y) { return ??? }; 

您可以通过将输入字符串中的时间解析为日期对象然后比较日期对象来执行此操作:

这里的工作演示: http : //live.datatables.net/erefom/2/edit#preview

来源: http : //live.datatables.net/erefom/2/edit

另请参阅此答案: 在Javascript中从用户输入中将时间解析为Date对象的最佳方法是什么?

从前面的例子中阐述; 即使时间单元格为空,下面的代码段也会排序。

 function getTimeValue(x) { // if the cell is not empty then parse it, otherwise just return 0 as the value; so it will be sorted appropriately. if (x != '') { var time = x.match(/(\d+)(?::(\d\d))?\s*(P?)/); var h = parseInt(time[1]) + (time[3] ? 12 : 0); if(!time[3] && parseInt(time[1])==12) h = 0; if(time[3] && parseInt(time[1])==12) h = 12; return h * 60 + ( parseInt(time[2]) || 0 ); } else { return 0; } } 

这对我有用

 jQuery.extend(jQuery.fn.dataTableExt.oSort, { "time-sort-pre": function(a) { if (a == '') return null; var time = a.match(/(\d+)(:(\d\d))?\s*(p?)/i); if (time == null) return null; var hours = parseInt(time[1], 10); if (hours == 12 && !time[4]) { hours = 0; } else { hours += (hours < 12 && time[4]) ? 12 : 0; } var d = new Date(); d.setHours(hours); d.setMinutes(parseInt(time[3], 10) || 0); d.setSeconds(0, 0); return d; }, "time-sort-asc": function(a, b) { return ((a < b) ? -1 : ((a > b) ? 1 : 0)); }, "time-sort-desc": function(a, b) { return ((a < b) ? 1 : ((a > b) ? -1 : 0)); } }); 

使用此答案中的一段代码从Javascript中的用户输入解析Date对象的时间是什么? 并且使用dataTables 1.9.4进行测试,需要在dataTables.js作为插件之后调用此代码,然后只需要将de sType设置为您的列{sType: "time-sort"} 。 例:

 $('#datatable-list').dataTable( aoColumns: [{sType: "time-sort"}] ); 

假设您的表只有一列包含时间值