jQuery - sorting DIVs by date

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.


  • Digg
  • del.icio.us
  • blogmarks
  • Reddit
  • Simpy
  • StumbleUpon
  • Technorati
  • description
  • Ma.gnolia
  • Slashdot
  • Sphinn
  • Spurl

Related Posts

Sponsored links


Tags: , , ,

Posts linking to this article:

What I’m reading - October 20th through October 21st
What I’m reading - October 20th through October 21st:. jQuery - sorting DIVs by date | ProDevTips - dev notes and tutorials - I just had to sort a list of DIVs by date with the newest date first. To add complexity to the problem the ...

[Web] 連結分享
PHP. phpQuery - PHP 處理HTML DOM 的好幫手阿! PHP 判斷Header 送出前, 是否有值被送出去: headers_sent(); [PHP]如何把Yahoo! BBAuth 加入網站入口認證; 可怕的phpmyadmin ,刪除操作要養成看訊息的習慣; Specifications for PHP5; Becoming a Kick-ass ...

Subscribe with Google Reader