Calculate the approximate time passed since an event

Usually, on the comments/articles section you need a function to calculate the aproximate time that passed since an event.

For example .. on a user profile page you write the last time when the user logged in : 2 days and 20 minutes ago .. no one cares that it was seen 2 days and 20 minutes ago or 2 days and 19 minutes ago .. usually a nice aproximation is more elegant .. something like I did for a gaming site few months ago “The user was last seen 2 days ago”.

For events that took place less than a day ago is better to show more details but still not too granular .. split it in hours OR minutes OR seconds.

Example of function output :
– 10 seconds ago
– 1 minute ago
– 5 hours ago
– 1 day ago
– 2 weeks ago
– 4 months ago
– 1 year ago

  1. function time_ago($timestamp)
  2. {
  3.         $difference = time()$timestamp;
  4.         $periods = array(‘second’, ‘minute’, ‘hour’, ‘day’, ‘week’, ‘month’, ‘year’);
  5.         $multiples = array(‘seconds’, ‘minutes’, ‘hours’, ‘days’, ‘weeks’, ‘months’, ‘years’);
  6.         $lengths = array(’60’, ’60’, ’24’, ‘7’, ‘4.35’, ’12’);
  7.         for ($i=0; $difference >= $lengths[$i]; $i++)
  8.         {
  9.                 $difference /= $lengths[$i];
  10.         }
  11.         $difference = round($difference);
  12.         if ($difference != 1)
  13.         {
  14.                 $periods[$i] = $multiples[$i];
  15.         }
  16.         $text = $difference.‘ ‘.$periods[$i];
  17.         return $text;
  18. }

If you wish to translate it to your language just edit the first 2 arrays :

  1. $periods = array(‘second’, ‘minute’, ‘hour’, ‘day’, ‘week’, ‘month’, ‘year’);
  2. $multiples = array(‘seconds’, ‘minutes’, ‘hours’, ‘days’, ‘weeks’, ‘months’, ‘years’);

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.