CSS Class Based on Date

I recently saw a tutorial on SimplePie’s site about using relative dates and I modified the function to output a CSS class rather than text. That way you can make newer stories bold, brighter, or bigger and older stories dimmed out or smaller. Use your imagination with CSS. 🙂

Here is the function

function create_age_css_class($date_sent)
$date_sent should be in the following format: YYYYMMDDHHMMSS
Based on doRelativeDate() By Garrett Murray, http://graveyard.maniacalrage.net/etc/relative/
$in_seconds = strtotime(substr($date_sent,0,8).' '.
$diff = time()-$in_seconds;
if ($diff < 86400)
$css_class = 'age_today';
else if ($diff < 604800)
$css_class = 'age_days';
else if ($diff < 1209600)
$css_class = 'age_week';
else if ($diff < 2630880)
$css_class = 'age_weeks';
$css_class = 'age_month';
return $css_class;

Here is how I call it

$data .= '<li><a href="'. $item->get_permalink();
$data .= ' class="' . create_age_css_class($item->get_date('YmdHis')) . '"';
$data .= '>';

You don’t have to use SimplePie for this function, but it’s what inspired me to modify it.

Now for an screenshot

Here is the HTML I used for that

<ul id="type3">
<li class="age_today">Lorem ipsum dolor sit amet</li>
<li class="age_days">Etiam iaculis nulla iaculis mauris</li>
<li class="age_week">Suspendisse at odio</li>
<li class="age_week">Nullam volutpat aliquam lacus</li>
<li class="age_weeks">Nunc dapibus eros vitae mauris rutrum laoreet</li>
<li class="age_weeks">Suspendisse sed nisl</li>
<li class="age_month">Nulla scelerisque gravida neque</li>
<li class="age_month">Leo imperdiet metus, ut adipiscing nisi lacus et pede</li>

And here is the CSS used

<style type="text/css">
body {font-family:Verdana, Arial, Helvetica, sans-serif; color:#000; background-color:#fff;}
ul {list-style:none;}
#type3 .age_days {font-size:150%; color:#555;}
#type3 .age_week {font-size:100%; color:#777;}
#type3 .age_weeks {font-size:80%; color:#999;}
#type3 .age_month {font-size:60%; color:#ccc;}

Added screenshot and sample CSS

Tags: , , ,

Comments 1-2 of 2 to “CSS Class Based on Date”

  1. 1 · Nadya says:

    Is there a demo of this? Also, where do I plug these bits of code? I don’t wanna mess things up. :o)

  2. 2 · blogger says:

    I added a screenshot and some sample CSS. If you use SimplePie you can just call it like I showed in the code above. But if you don’t use SimplePie you just need to send the date in ‘YmdHis’ format or convert it using PHP’s date() function.

    For instance you’re comment was posted on Oct 3, 2008 at 6:13 pm so I would send this to the function (assuming the seconds value when you posted was zero).

    echo '<li class="' . create_age_css_class('20081003181300') . '">your comment title</li>';

    You could use this for WordPress blog comments, forum posts or whatever.

Leave a Comment

Comments are reviewed before publishing to prevent spam.