我使用 Jquery 数据表 (http://datatables.net/)。您可以扩展插件以添加新的“数据格式”。
例子:
我来自西班牙,日期用以下格式表示:dd/mm/yyyy hh:mm:ss。
如果我使用插件用来排序日期的排序器,日期就像字符串一样排序(插件假设数据格式为 yyyy-mm-dd hh:mm:ss)。
您必须执行一个函数来返回一个整数,该整数是日期的“权重”,“20/10/2013”的权重小于“15/11/2013”,因此 20/10/2013 小于2013 年 15 月 11 日。
对于dd/mm/yyyy的格式,计算权重的函数是:(可以改成mm/dd/yyyy改变frDateParts的索引)
function dateHeight(dateStr){
if (trim(dateStr) != '') {
var frDate = trim(dateStr).split(' ');
var frTime = frDate[1].split(':');
var frDateParts = frDate[0].split('/');
var day = frDateParts[0] * 60 * 24; /*<--- in mm/dd/yyyy is frDateParts[1]*/
var month = frDateParts[1] * 60 * 24 * 31; /*<--- in mm/dd/yyyy is frDateParts[0]*/
var year = frDateParts[2] * 60 * 24 * 366;
var hour = frTime[0] * 60;
var minutes = frTime[1];
var x = day+month+year+hour+minutes;
} else {
var x = 99999999999999999;
}
return x;
}
以及插件的扩展名:
/* NOTE: the new format is called "date-euro" (why not? xD) so:
you have to do the "date-euro-asc" for ascendent order and the "date-euro-desc"
for descendent order. the return of the function has to be
-1 (lesser), 0 (equal) or 1 (greater)*/
jQuery.fn.dataTableExt.oSort['date-euro-asc'] = function(a, b) {
var x = dateHeight(a);
var y = dateHeight(b);
var z = ((x < y) ? -1 : ((x > y) ? 1 : 0));
return z;
};
jQuery.fn.dataTableExt.oSort['date-euro-desc'] = function(a, b) {
var x = dateHeight(a);
var y = dateHeight(b);
var z = ((x < y) ? 1 : ((x > y) ? -1 : 0));
return z;
};
当您使用 datetables 插件定义该列的表时:
{ "sType": "date-euro"},
示例(包含 5 列的表(Int、string、Date、string、string):
"aoColumns": [
{ "sType": 'numeric' },
null,
{ "sType": "date-euro"},
null,
null
],