How to sort date in n-day/week/month/year format?
How to sort date in n-day/week/month/year format?
ernestin123
Posts: 3Questions: 1Answers: 0
I have a table that displays the 'freshness' of posts in this format:
30 second,
1 week
3 day,
5 month
But I can't figure out how to sort them, this is what I've achieved so far:
function getRank(name) {
//newname = name.slice(2,name.length);
//alert(name);
newname = name;
var rankNumber;
if (newname == "1 day"){
rankNumber = 1;
} else if (newname == "week"){
rankNumber = 2;
} else if (newname == "month") {
rankNumber = 3;
} else if (newname == "year") {
rankNumber = 4;
}
console.log(newname);
return rankNumber + parseInt(name.slice(0,1));
}
jQuery.fn.dataTableExt.oSort["rank-desc"] = function (x, y) {
return getRank(x) < getRank(y);
};
jQuery.fn.dataTableExt.oSort["rank-asc"] = function (x, y) {
return getRank(x) > getRank(y);
}
$(document).ready(function () {
var oTable = $('#topics').dataTable({
"autoWidth": false,
"bLengthChange": false,
"fixedColumns": true,
"aoColumnDefs" : [{
"bSortable" : true,
"aTargets" : [5],
"sType": "rank"
}]
});
Edited by Allan - Syntax highlighting. Details on how to highlight code using markdown can be found in this guide.
This question has an accepted answers - jump to answer
This discussion has been closed.
Answers
You need to convert the string based information into numbers (i.e. something that can be easily sorted). You could split on the space and then multiple the number by the number of seconds in the unit given for example - then you would be sorting in seconds intervals.
Allan
This is a great answer, thank you allan, however I'm still having trouble.
This is my code:
However the sorting algorithm is not working properly:
You can see the working algorithm in www.gradtheorem.com
Thank you for all the help
Could you change:
to be:
and likewise (inverted logic) for the
asc
method.Allan
Oh wow thank you Allan!
It works now
Thank you very very much