Owen Owen - 5 months ago 24
Javascript Question

Sorting a table using jQuery based on date values

I'm having a problem very similar to this question: jQuery table sort

When the Date header is clicked, I want to sort the table rows based on the dates, not based on the text.

I've based my code on this jsFiddle http://jsfiddle.net/gFzCk/ which was one of the answers to the above question, and it does sort, but it treats the date as normal text, not as a date.

Normally I'd be able modify the original code to suit my needs, but this code is just a little beyond me.

Here's my jsFiddle http://jsfiddle.net/S6dM6/


<th id="dateHeader">Date</th>
<th>Phone #</th>
<th id="city_header">City</th>
<td>New York</td>


var table = $('table');

.wrapInner('<span title="sort this column"/>')

var th = $(this),
thIndex = th.index(),
inverse = false;



return $(this).index() === thIndex;

}).sortElements(function(a, b){

return $.text([a]) > $.text([b]) ?
inverse ? -1 : 1
: inverse ? 1 : -1;

}, function(){

// parentNode is the element we want to move
return this.parentNode;


inverse = !inverse;



And this js file is referenced:

Just in case you're going to suggest some kind of table sorting plugin, note that my end result wont be sorting when the header is clicked, the sort function will be called from various places in my javascript, I'm just using this click example as a simple starting point to get the concept working and as a simple way to put this question.


Modify your sortElements method like this:

        }).sortElements(function(a, b){

            var strDate = $.text ([a]);
            var dateParts = strDate.split("/");
            var date = new Date(dateParts[2], (dateParts[1] - 1), dateParts[0]);
            var a1 = date.getTime ();
            strDate = $.text ([b]);
            dateParts = strDate.split("/");
            date = new Date(dateParts[2], (dateParts[1] - 1), dateParts[0]);
            b1 = date.getTime ();

            return a1 > b1 ?
                inverse ? -1 : 1
                : inverse ? 1 : -1;