我想排序表中的一个表中的javascript日期对象。日期的格式为mm/dd/yyyy hr:min a.m.当我尝试按日期排序时,点击标题,什么也没有发生。我可以根据其他列进行排序。 console.log语句是为了调试目的而添加的 - 您可以忽略这些语句。如何使用javascript排序日期对象tablesorter?
$.tablesorter.addParser({
id: "customDate",
is: function(s) {
//return false;
//use the above line if you don't want table sorter to auto detected this parser
//else use the below line.
//attention: doesn't check for invalid stuff
//2009-77-77 77:77:77.0 would also be matched
//if that doesn't suit you alter the regex to be more restrictive
var passes = /\d{1,2}\/\d{1,2}\/\d{1,4}\s\d{1,2}:\d{1,2}\s[ap]\.m\./.test(s);
return passes;
},
format: function(s) {
s = s.replace(/\-/g," ");
s = s.replace(/:/g," ");
s = s.replace(/\./g," ");
s = s.replace(/\//g," ");
s = s.replace(/a\sm/, 1);
s = s.replace(/p\sm/, 2);
s = s.split(" ");
console.log('am or pm: ' + s[5]);
console.log('hour == ' + s[3]);
if (s[3] == '12' && s[5] == 1){
s[3] = 0; //convert 12am to 0 hours.
console.log('new hour -- 12am: ' + s[3]);
}
else if (s[5] == 2 && s[3] != '12'){
s[3] = parseInt(s[3]) + 12; //convert p.m. hours to military time format if it isn't noon.
console.log('new hour -- pm: ' + s[3]);
}
console.log('minutes: ' + parseInt(s[4]));
console.log();
return $.tablesorter.formatFloat(new Date(s[2], s[0], s[1], s[3], s[4],0,0,0));
},
type: "numeric"
});
您需要从一个月数subract 1(S [0]),以获得正确的日期根据月在javascript日期对象是零。但是,它不会影响排序,因为所有日期都会超出一个月。 24小时不是“军事时间格式”,它在世界大部分地区被平民广泛使用,例如,航空公司。 – RobG