Reputation: 1173
Really stuck on big problem. I need to sort a date column.But the date format is `mm/dd/yyyy hh:mmAM/PM. I tried till
jQuery.fn.dataTableExt.oSort['uk_date-asc'] = function(a,b) {
var ukDatea = $(a).text().split('/');
var ukDateb = $(b).text().split('/');
var x = (ukDatea[2] + ukDatea[0] + ukDatea[1]) * 1;
var y = (ukDateb[2] + ukDateb[0] + ukDateb[1]) * 1;
console.log("here");
return ((x < y) ? -1 : ((x > y) ? 1 : 0));
};
jQuery.fn.dataTableExt.oSort['uk_date-desc'] = function(a,b) {
var ukDatea = $(a).text().split('/');
var ukDateb = $(b).text().split('/');
var x = (ukDatea[2] + ukDatea[0] + ukDatea[1]) * 1;
var y = (ukDateb[2] + ukDateb[0] + ukDateb[1]) * 1;
return ((x < y) ? 1 : ((x > y) ? -1 : 0));
}
but now i don't have any idea how to include time .Please guys help me.
Upvotes: 2
Views: 5565
Reputation: 1258
I had to format and sort using mm/dd/yyyy format, so i had to do some changes...
$("#tblSearch").DataTable({
"processing": true, // for show progress bar
"filter": false, // this is for disable filter (search box)
"orderMulti": false, // for disable multiple column at once
"bDestroy": true,
"order": [[1, "asc"]],
data: data,
"columns": [
],
"language": {
"emptyTable": "We couldn't find any result for the search"
},
"columnDefs": [
{
data: "date", "sType": "date-mmddyyyy", className: 'text-center', targets: [0]
, "mRender": function (d, type, full) {
d = new Date(d);
month = '' + (d.getMonth() + 1),
day = '' + d.getDate(),
year = d.getFullYear();
if (month.length < 2)
month = '0' + month;
if (day.length < 2)
day = '0' + day;
return [month, day, year].join('/');
} }
],
});
jQuery.extend(jQuery.fn.dataTableExt.oSort, {
"date-mmddyyyy-pre": function (a) {
var dateFormat = a.split('/');
return (dateFormat[2] + dateFormat[0] + dateFormat[1]) * 1;
},
"date-mmddyyyy-asc": function (a, b) {
return ((a < b) ? -1 : ((a > b) ? 1 : 0));
},
"date-mmddyyyy-desc": function (a, b) {
return ((a < b) ? 1 : ((a > b) ? -1 : 0));
}
});
Upvotes: 0
Reputation: 85558
If the format is mm/dd/yyyy hh:mmAM/PM
, then all there is needed for this format to be a Date.parse()
compliant format is to insert a space between minutes mm
and AM
/ PM
. So if you do this, you can use the returned value from Date.parse()
to compare the dates including the time :
jQuery.fn.dataTableExt.oSort['uk_date-pre'] = function(a) {
a = a.slice(0,-2)+' '+a.slice(-2);
var date = Date.parse(a);
return typeof date === 'number' ? date : -1;
}
jQuery.fn.dataTableExt.oSort['uk_date-asc'] = function(a,b) {
return ((a < b) ? -1 : ((a > b) ? 1 : 0));
}
jQuery.fn.dataTableExt.oSort['uk_date-desc'] = function(a,b) {
return ((a < b) ? -1 : ((a > b) ? -1 : 0));
}
see demo -> http://jsfiddle.net/ttfrxmsk/
The following timestamps is used by the demo :
01/27/2011 10:20PM
01/27/2011 10:19PM
01/27/2011 10:19AM
10/13/2014 4:10PM
04/12/2011 11:20AM
10/13/2013 4:20PM
08/01/2012 10:20PM
07/10/2014 7:00AM
08/01/2012 10:20PM
07/10/2014 7:00AM
Upvotes: 4