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:

1284121336 (Fri, 10 Sep 2010 22:22:16 +1000) is 1 week away
1283257336 (Tue, 31 Aug 2010 22:22:16 +1000) is 3 days ago
1283520136 (Fri, 03 Sep 2010 23:22:16 +1000) is 1 hour away
1283516608 (Fri, 03 Sep 2010 22:23:28 +1000) is 1 min away
1283516514 (Fri, 03 Sep 2010 22:21:54 +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.