I just had to sort a list of DIVs by date with the newest date first. To add complexity to the problem the dates could be either in Atom or RSS2 format. The sorting itself is done with TinySort. A really useful little library.

The HTML looks like this:

<div class="article_cont"> <span class="hide_me_date">Atom or RSS2 date here</span> ... </div> <div class="article_cont"> <span class="hide_me_date">Atom or RSS2 date here</span> ... </div> ...

And the Javascript with irrelevant parts cut out:

function parseDate(d){ var res = d.match(/\d\d\d\d-\d\d-\d\d/); if(res){ Date.format = "yyyy-mm-dd"; var dt = new Date(res[0]); }else var dt = new Date(d); return dt.getTime(); } ... $(".hide_me_date").each(function(i){ $(this).html( parseDate( $(this).html() ) ); }); $(".article_cont").tsort(".hide_me_date", {order:"desc"}); ...

In case we have an Atom date we get the juicy part through the match in parseDate. If we got a match we create a date with it, if we don’t have a match we have RSS2 instead in which case we can just use the date as is. At the end we return the number of microseconds since 1977 or something like that, it doesn’t matter as long as we got something we can sort by.

When we loop through all SPANs with the hide_me_date class, the parseDate function is used to switch the original Atom or RSS2 dates into a microsecond integer which we finally use in conjunction with tsort.

Note the dependency on date.js.





Related Posts