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

function time_ago($timestamp)
{
	$difference = time() - $timestamp;
	$periods = array('second', 'minute', 'hour', 'day', 'week', 'month', 'year');
	$multiples = array('seconds', 'minutes', 'hours', 'days', 'weeks', 'months', 'years');
	$lengths = array('60', '60', '24', '7', '4.35', '12');
	for ($i=0; $difference >= $lengths[$i]; $i++)
	{
		$difference /= $lengths[$i];
	}
	$difference = round($difference);
	if ($difference != 1)
	{
		$periods[$i] = $multiples[$i];
	}
	$text = $difference.' '.$periods[$i];
	return $text;
}	

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

$periods = array('second', 'minute', 'hour', 'day', 'week', 'month', 'year');
$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.