Reputation: 295
I am using datatable plugin version 1.8.2 for displaying table on my webpage.
It is working fine except. It is not sorting dates properly, it is showing "invalid date" in Date object. below is my code snippet.
$(document).ready(function() {
jQuery.fn.dataTableExt.oSort['usdate-asc'] = function(a,b) {
/*
a and b are <div> tag with date
*/
var texta = ($(a).text()).toString(); // Here I am able to see my date in ' 03-17-2015 12:25:21 AM ' format
var textb = ($(b).text()).toString();// Here I am able to see my date in ' 03-17-2015 12:25:21 AM ' format
var usDatea = new Date(Date.parse(texta)); // Here it is showing "invalid date"
var usDateb = new Date(Date.parse(textb));
return ((usDatea < usDateb) ? -1 : ((usDatea > usDateb) ? 1 : 0));
};
jQuery.fn.dataTableExt.oSort['usdate-desc'] = function(a,b) {
/*
a and b are <div> tag with date
*/
var texta = ($(a).text()).toString(); //same as above
var textb = ($(b).text()).toString(); //same as above
var usDatea = new Date(Date.parse(texta)); //same as above
var usDateb = new Date(Date.parse(textb)); //same as above
return ((usDatea < usDateb) ? 1 : ((usDatea > usDateb) ? -1 : 0));
};
$('#tablegridname').dataTable( {
"sPaginationType": 'full_numbers',
"bJQueryUI": true,
"iDisplayLength": 50,
"aLengthMenu":[50,100,500,1000],
"aaSorting": [[ 4, 'desc' ]],
"aoColumns": [null, null, null, null, {"sType": "usdate"}]
} );
});
});
Upvotes: 0
Views: 802
Reputation: 4759
Try this fiddle:
It uses this simple function:
function parseDateForSort(d)
{
return d.substring(6,10) + d.substring(0,2) +
d.substring(3,5) + d.substring(20) +
d.substring(11,19);
}
The function takes advantage of the fact that, luckily, PM comes after AM alphabetically; hence the "d.substring(20)" in the middle of the string. So we have YYYYMMDD[AM or PM]HH:MM:SS.
In your code you can get rid of Date.parse, and replace your return with:
usDatea = parseDateForSort(texta);
usDateb = parseDateForSort(textb);
return ((usDatea < usDateb) ? -1 : ((usDatea > usDateb) ? 1 : 0));
Good luck.
Addendum:
You can create your own sort type, and then specify the column thusly:
$.extend($.fn.dataTableExt.oSort, {
"date-us-pre": function (v) {
return parseDateForSort(v);
},
"date-us-asc": function ( a, b ) { return a - b; },
"date-us-desc": function ( a, b ) { return b - a; }
} );
And then in your .dataTable call include
"aoColumnDefs": [ { "sType":"date-us", "aTargets":[6] } ]
or whatever column number it is instead of 6.
Upvotes: 1