如何使用tablesorter按javascript日期对象排序?

如何使用tablesorter按javascript日期对象排序?,javascript,sorting,date,tablesorter,Javascript,Sorting,Date,Tablesorter,我正在尝试对其中一列中包含javascript日期对象的表进行排序。日期的形式是mm/dd/yyyy hr:min a.m.当我尝试按日期排序时,我单击标题,但什么也没有发生。我可以按其他列进行排序。添加console.log语句是为了调试目的——您可以忽略这些语句 $.tablesorter.addParser({ id: "customDate", is: function(s) { //return false;

我正在尝试对其中一列中包含javascript日期对象的表进行排序。日期的形式是mm/dd/yyyy hr:min a.m.当我尝试按日期排序时,我单击标题,但什么也没有发生。我可以按其他列进行排序。添加console.log语句是为了调试目的——您可以忽略这些语句

$.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"
    });

使用:20111117,您可以按字母顺序排序。

嗯,我解决了自己的问题。如果我对date对象调用getTime(),它将返回日期的数值,并且我能够对其进行排序

这行代码现在看起来像:

return $.tablesorter.formatFloat(new Date(s[2], s[0], s[1], s[3], s[4],0,0,0).getTime()); 

UTC不是日期格式,而是时区。您要查找的是ISO8601格式,它是日期的yyyy-mm-dd,可能包括时间和区域。如果您是建议的,那么请注意
字符串的内容取决于实现
。您需要从月份编号(s[0])中减去1以获得正确的日期,因为在javascript日期对象中,月份是以零为基础的。但是,它不会影响排序,因为所有日期都将在一个月前过期。而且24小时制不是“军事时间制”,它被世界上大部分地区的平民广泛使用,例如航空公司。