2012-07-03 27 views
0

這裏是代碼..jQuery的數據表按日期排序錯誤

 $.fn.dataTableExt.oSort['us_date-asc'] = function (a, b) { 

     var x = new Date(a), 
     y = new Date(b); 
     return ((x < y) ? -1 : ((x > y) ? 1 : 0)); 
    }; 

    $.fn.dataTableExt.oSort['us_date-desc'] = function (a, b) { 
     var x = new Date(a), 
     y = new Date(b); 
     return ((x < y) ? 1 : ((x > y) ? -1 : 0)); 
    }; 

    var oTable = $('#example').dataTable({ 
     "bJQueryUI": true, 
     "sPaginationType": "full_numbers", 
     //"bSortClasses": false, 
     "aoColumns": [ 
     null, null, 
     { 
      "sType": "us_date" 
     }, 
     null, 
     { 
      "bSortable": false 
     }], 
     "aaSorting": [ 
      [2, "desc"] 
     ] 
    }); 

正在使用此代碼爲數據表,使第三列排序。 我想以jun-06-2012格式顯示日期。當我使用06-06-2012格式時,排序工作正常......但排序不起作用(它在chrome中工作,但在其他瀏覽器中不起作用)按字母順序... 我該如何解決這個問題?任何幫助將不勝感激

回答

1
jQuery.fn.dataTableExt.oSort['shortdate-asc'] = function(x,y) { 
     var months = {}; 
       months["JAN"] = "01"; 
       months["FEB"] = "02"; 
       months["MAR"] = "03"; 
       months["APR"] = "04"; 
       months["MAY"] = "05"; 
       months["JUN"] = "06"; 
       months["JUL"] = "07"; 
       months["AUG"] = "08"; 
       months["SEP"] = "09"; 
       months["OCT"] = "10"; 
       months["NOV"] = "11"; 
       months["DEC"] = "12"; 

     x = (x=="")? 0 : x.split('-'); 
     y = (y=="")? 0 : y.split('-'); 

     if(x.length){ 
      x = x[2] + months[x[0].toUpperCase()] + x[1]; 
     } 

     if(y.length){ 
      y = y[2] + months[y[0].toUpperCase()] + y[1]; 
     } 



     return ((x < y) ? -1 : ((x > y) ? 1 : 0)); 
    }; 


    jQuery.fn.dataTableExt.oSort['shortdate-desc'] = function(x,y) { 

     var months = {}; 
       months["JAN"] = "01"; 
       months["FEB"] = "02"; 
       months["MAR"] = "03"; 
       months["APR"] = "04"; 
       months["MAY"] = "05"; 
       months["JUN"] = "06"; 
       months["JUL"] = "07"; 
       months["AUG"] = "08"; 
       months["SEP"] = "09"; 
       months["OCT"] = "10"; 
       months["NOV"] = "11"; 
       months["DEC"] = "12"; 

     x = (x=="")? 0 : x.split('-'); 
     y = (y=="")? 0 : y.split('-'); 

     if(x.length){ 
      x = x[2] + months[x[0].toUpperCase()] + x[1]; 
     } 

     if(y.length){ 
      y = y[2] + months[y[0].toUpperCase()] + y[1]; 
     } 

     return ((x < y) ? 1 : ((x > y) ? -1 : 0)); 
    }; 
+0

感謝兄弟...它的工作........... – Shanib

0

你可以使用一個像庫向datejs arbit字符串轉換爲實際日期的對象和比較這些。這個想法是將你展示的內容與你實際比較的內容分開。

示例代碼:

var x = Date.parse('06-jun-2012'); 
var y = Date.parse('06-jul-2012'); 
return Date.compare(x, y); 

您可以使用日期對象的toString()方法,並指定一個自定義格式字符串。檢查文檔http://code.google.com/p/datejs/wiki/APIDocumentation

如果碰巧是一次性任務,您可能不想採用另一個庫的依賴關係。但是,如果您恰巧在整個應用程序中操縱日期,那麼您會希望使用此庫。