Take the 2-minute tour ×

I'm trying to sort a table with javascript Date objects in one of the columns. The form of the date is mm/dd/yyyy hr:min a.m. When I try to sort by the date, I click on the header, and nothing happens. I can sort by the other columns just fine. The console.log statements were added for debugging purposes -- you can ignore those.

        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]));

        return $.tablesorter.formatFloat(new Date(s[2], s[0], s[1], s[3], s[4],0,0,0)); 
        type: "numeric"
share|improve this question
You need to subract 1 from the month number (s[0]) to get the correct date as months are zero based in javascript date objects. However, it won't affect the sort as all dates will be out by one month. And 24hr time isn't "military time format", it is widely used by civilians in most parts of the world, e.g. airlines. –  RobG Nov 18 '11 at 0:36
add comment

2 Answers

Use the UTC date format: 20111117 and you can sort it alphabetically.

share|improve this answer
UTC isn't a date format, it's a time zone. What you are looking for is ISO8601 format, which is yyyy-mm-dd for a date and might include time and zone. If you are suggesting Date.prototype.toUTCString() then be aware that The contents of the String are implementation-dependent. –  RobG Nov 18 '11 at 0:28
add comment
up vote 0 down vote accepted

Well, I fixed my own problem. If I call getTime() on my date object, it returns a numerical value for the date, and i'm able to sort that.

That line of code now looks like:

return $.tablesorter.formatFloat(new Date(s[2], s[0], s[1], s[3], s[4],0,0,0).getTime()); 
share|improve this answer
add comment

Your Answer


