Drupal time ago function in template.php

User login

Would you like to make time appear as an interval like "4 days 3 hours ago"? Possibly you have worked with such formatters (drupal time ago) in views and date fields, but what about editing a node.tpl.php for example? Or programmaticaly include the last login time of a node's author, as time ago, in a block?

It comes in handy when there is a reusable function to format our time statements as drupal time ago - and php in general. So here comes a little function to be included in the template.php file. You can easily use it in your themes to display a timestamp as "Time ago".

function ago($timestamp){
   $difference = time() - $timestamp;
   $periods = array("second", "minute", "hour", "day", "week", "month", "years", "decade");
   $lengths = array("60","60","24","7","4.35","12","10");
   for($j = 0; $difference >= $lengths[$j]; $j++)
   $difference /= $lengths[$j];
   $difference = round($difference);
   if($difference != 1) $periods[$j].= "s";
   $text = "$difference $periods[$j] ago";
   return $text;
  }

There. After clearing all caches you would be able to use the above by inserting a timestamp like print ago($field->timestamp). Or print when a user last logged in as time ago, like

  global $user;
  echo "Last login: ".ago($user->login);

The above code was taken from http://www.php.net/manual/en/function.time.php

Tags: 
Drupal 6, Drupal theming, Drupal Quick Tips