Twitter like date format in WordPress

A tiny bit of code to make your dates more human readable by writing them the Twitter way; “3 days ago” or “7 hours ago”.

I found a nice article on Techalby.com on how to format your dates the Twitter way. However, the dates weren’t localized and the function only worked as a filter. I made a few adjustments so the date gets localized and you can you use it anywhere in your theme without depending on a filter. See the comments in the code on how to use it.

// add_filter('the_time', 'dynamictime'); // uncomment if you want to use the filter
function dynamictime($p = null) 
{
  global $post;
  if (!$p) $p = $post; // pass the post object as the first parameter, defaults to the current post if left empty
  $date = $p->post_date;
  $time = get_post_time('G', true, $p);
  $mytime = time() - $time;
  if($mytime > 0 && $mytime < 7*24*60*60) // use twitter like date format if not older than one week (7 days)
    $mytimestamp = sprintf(__('%s ago'), human_time_diff($time));
  else
    $mytimestamp = date_i18n(get_option('date_format'), strtotime($date));
  return $mytimestamp;
}