2011-11-17 59 views
1

我想排序表中的一個表中的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" 
    }); 
+0

您需要從一個月數subract 1(S [0]),以獲得正確的日期根據月在javascript日期對象是零。但是,它不會影響排序,因爲所有日期都會超出一個月。 24小時不是「軍事時間格式」,它在世界大部分地區被平民廣泛使用,例如,航空公司。 – RobG

回答

0

嗯,我解決了我自己的問題。如果我在我的日期對象上調用getTime(),它會返回日期的數字值,並且我可以對其進行排序。

這行代碼現在看起來像:

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

使用UTC date format:20111117,您可以按字母順序對其進行排序。

+1

UTC不是日期格式,它是一個時區。您正在尋找的是ISO8601格式,日期爲yyyy-mm-dd,可能包括時間和區域。如果您建議[Date.prototype.toUTCString()](http://es5.github.com/#x15.9.5.42),那麼請注意'String的內容是依賴於實現的'。 – RobG