April 25, 2007

PHP relative time function

I couldn’t find a PHP function that would take a number of seconds as input and give me something like “3 weeks and 2 days” so I put this together:

function rel_time($seconds){
	if($seconds < 60){
		if($seconds < 0){ $seconds = 0; }
		switch($seconds){
			case 1:
				return "1 second";
				break;
			default:
				return "$seconds seconds";
				break;
		}
	}else{
		$date_push = array();
		$time_units = array(	'year'		=> (365*24*60*60),
					'month'		=> (30*24*60*60),
					'week'		=> (7*24*60*60),
					'day'		=> (24*60*60),
					'hour'		=> (60*60),
					'minute'	=> (60));
		foreach($time_units as $unit=>$unit_time){
			$total = 0;
			if($unit=='day' && count($date_push) && ($seconds < $time_units['day'])){
				$seconds = 0;
			}
			while($seconds >= $unit_time){
				$seconds -= $unit_time;
				$total++;
			}
			switch ($total){
				case 0:
					break;
				case 1:
					$date_push[] = "1 $unit";
					break;
				default:
					$date_push[] = "$total {$unit}s";
					break;
			}
			if(count($date_push) == 2){
				break;
			}
		}
		return implode(" and ", $date_push);
	}
}

Example usage:

$rel_time  = rel_time(time() - $timestamp);
print "Posted $rel_time ago";

It’s not as efficient as it could be, but it gets the job done for now. And it’s pretty easy to configure it for the time units that you want to use.

No Responses

Leave a Reply