Bug Fix for Sortable Table – Sorting Date functionality

Sortable Table is a great javascript library for client side sorting of HTML table. Its under Apache 2.0 license so its very compatible. Recently I faced a bug when sorting date columns. It was not sorting the dates properly. After some debugging I got to know that the library assumes the date format to be yyyy-mm-dd. See line 287 or search for case "date".

var parts = sText.split("-");
var d = new Date(0);
d.setFullYear(parts[0]);
d.setDate(parts[2]);
d.setMonth(parts[1] - 1);
return d.valueOf();

Now to make it compatible with your date format say mm/dd/yyyy. You need to update it as

var parts = sText.split(" ");
parts[0] = sText;
var date1 = parts[0].split("/");
var d = new Date(0);
d.setFullYear(1970 + parseInt(date1[2]), date1[0], date1[1]);
d.setHours(0);
d.setMinutes(0);
return d.valueOf();

The new version is v1.12 and it still has this problem. The code in the new version is
SortableTable.toDate = function (s) {
var parts = s.split("-");
var d = new Date(0);
d.setFullYear(parts[0]);
d.setDate(parts[2]);
d.setMonth(parts[1] - 1);
return d.valueOf();
};

You need to update this snippet to reflect your date format. You can reuse the above code. I am thinking of rewriting date parsing part to parse the date in any given format. So the fix becomes much generic. Will update once I do that.

Update: The present one allows you to add new data formats using prototype. So you can add your date as a new format, you need to implement metod_to_compare which returns 0 or 1

SortableTable.prototype.addSortType("new_data_type", null, function (s1, s2) {
return s1.metod_to_compare(s2);
});

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.