Darkness Reigns (two-point-oh)

PHP function for displaying relative dates in a human readable format

Date: 2007-03-29

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", "years", "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:

1215787613 (Sat, 12 Jul 2008 00:46:53 +1000) is 1 week away
1214923613 (Wed, 02 Jul 2008 00:46:53 +1000) is 3 days ago
1215186413 (Sat, 05 Jul 2008 01:46:53 +1000) is 1 hour away
1215182885 (Sat, 05 Jul 2008 00:48:05 +1000) is 1 min away
1215182791 (Sat, 05 Jul 2008 00:46:31 +1000) is 22 secs ago
Darkness Reigns : personal webspace of John McClumpha - © Copyright 2007, John McClumpha
Design: Incite Graphics
Hosting: Hosted Internet Services

Total users online is: 1 of which 0 are registered users.