Reputation: 288
I'm working on a project where I am receiving a date for a jQuery DataTable as a string format (mm/dd/yyyy). When I do a sort it sorts it like a string which causes causes it to be grouped in month order which is incorrect. I would like to use 'sType: date' to handle the sorting but since it is not a date object it won't sort it. Is there a way I can parse it to a date as it is being added into the data table?
I did find another way of doing this and sorting it properly but it only works in browsers other than ie8 (the table has ~1000 rows and it causes the script timeout error, chrome does it instantly)
jQuery.fn.dataTableExt.oSort['us_date-asc'] = function(a,b) {
if($(a).text()=="" && $(b).text()==""){
return 0;
}
else if($(a).text()=="" || $(b).text()==""){
return $(a).text()=="" ? -1 : 1;
}
else{
var x = new Date($(a).text());
var y = new Date($(b).text());
return ((x < y) ? -1 : ((x > y) ? 1 : 0));
}
};
jQuery.fn.dataTableExt.oSort['us_date-desc'] = function(a,b) {
if($(a).text()=="" && $(b).text()==""){
return 0;
}
else if($(a).text()=="" || $(b).text()==""){
return $(a).text()=="" ? 1 : -1;
}
else{
var x = new Date($(a).text());
var y = new Date($(b).text());
return ((x < y) ? 1 : ((x > y) ? -1 : 0));
}
};
I can then use this with
"sType": 'us_date'
Any suggestions on what I can do?
Upvotes: 1
Views: 1066
Reputation: 288
I managed to get this barely working in IE8 without causing a page timeout. It takes ~2 seconds to sort ~1000 records with 14 columns. (5 hidden columns). Chrome does it instantly.
jQuery.fn.dataTableExt.oSort['us_date-pre'] = function(a){
if($(a).text()==""){
return "19000101" * 1;
}
else{
var usDatea = $(a).text().split('/');
return (usDatea[2] + usDatea[0] + usDatea[1]) * 1;
}
}
jQuery.fn.dataTableExt.oSort['us_date-asc'] = function(a,b) {
return ((a < b) ? -1 : ((a > b) ? 1 : 0));
};
jQuery.fn.dataTableExt.oSort['us_date-desc'] = function(a,b) {
return ((a < b) ? 1 : ((a > b) ? -1 : 0));
};
Upvotes: 1