john.mcclumpha

php : PHP function for displaying relative dates in a human readable format

Published: 2 yearss ago

Here's a handy PHP function I use for comparing times and displaying the difference in a human-readable format.

The function itself returns the nearest approximate time based on the largest value from: decades, years, months, weeks, days, hours, minutes or seconds

function RelativeTime($timestamp){
	$difference = time() - $timestamp;
	$periods = array("sec", "min", "hour", "day", "week", "month", "year", "decade");
	$lengths = array("60","60","24","7","4.35","12","10");

	if ($difference > 0) { // this was in the past
		$ending = "ago";
	} else { // this was in the future
		$difference = -$difference;
		$ending = "to go";
	}		
	for($j = 0; $difference >= $lengths[$j]; $j++)
		$difference /= $lengths[$j];
	$difference = round($difference);
	if($difference != 1) $periods[$j].= "s";
	$text = "$difference $periods[$j] $ending";
	return $text;
}

examples:

1201698186 (Thu, 31 Jan 2008 00:03:06 +1100) is 1 week away
1200834186 (Mon, 21 Jan 2008 00:03:06 +1100) is 3 days ago
1201096986 (Thu, 24 Jan 2008 01:03:06 +1100) is 1 hour away
1201093458 (Thu, 24 Jan 2008 00:04:18 +1100) is 1 min away
1201093364 (Thu, 24 Jan 2008 00:02:44 +1100) is 22 secs ago

recent posts

Follow me on Twitter
Follow me on Facebook

Have you checked out Mister Wong? Simply the best way to manage your bookmarks online:
Mister Wong