Reputation: 19327
Ok I do have a javascript code that sort rows by Date in a HTML table. Now what I did there was to convert the dates to timestamp and sort them by native sort() javascript function but it seems the sorting was not right. what is the problem? is sorting date with timestamp incorrect?
here is what i have done so far
var asc = true;
function sortTable() {
var tbl = document.getElementById("mytable").tBodies[0];
var store = [];
for (var i = 0, len = tbl.rows.length; i < len; i++) {
var row = tbl.rows[i];
var rowdatedata = row.cells[1].textContent;
var rowdatesplit = rowdatedata.split('/');
var rowdatetimestamp = Math.round(new Date(parseInt(rowdatesplit[0]), parseInt(rowdatesplit[1]) - 1, parseInt(rowdatesplit[2]), 0, 0, 0).getTime() /1000);
if (!isNaN(rowdatetimestamp)) store.push([rowdatetimestamp, row]);
}
if (asc) {
store.sort(function(x, y) {
return x[0] - y[0];
});
document.getElementById('dateCol').textContent = 'Date ↑';
asc = false;
}
else {
store.sort(function(x, y) {
return y[0] - x[0];
});
document.getElementById('dateCol').textContent = 'Date ↓';
asc = true;
}
for (var i = 0, len = store.length; i < len; i++) {
var idno = i + 1;
store[i][1].cells[0].textContent = idno.toString();
tbl.appendChild(store[i][1]);
}
store = null;
}
http://jsfiddle.net/laupkram/kCxKn/
NOTE: just click the "Date" header and it will sort
ASCENDING ORDER RESULTS
ID Date ↑ Name
1 2012/08/15 Lerry
2 2012/03/16 Ansley
3 2012/05/18 Robinson
4 2012/10/05 Mp
DESCENDING ORDER RESULTS
ID Date ↓ Name
1 2012/10/05 Mp
2 2012/05/18 Robinson
3 2012/03/16 Ansley
4 2012/08/15 Lerry
Upvotes: 0
Views: 3774
Reputation: 4479
The problem is how parseInt
works, if the number starts with 0 it treats is as octal number. You have to do parseInt(value, 10)
to ensure the decimal conversion.
Upvotes: 3