Return to Snippet

Revision: 27464
at June 9, 2010 18:23 by LuckyShot


Updated Code
function relativedate($secs) {
		$second = 1;
		$minute = 60;
		$hour = 60*60;
		$day = 60*60*24;
		$week = 60*60*24*7;
		$month = 60*60*24*7*30;
		$year = 60*60*24*7*30*365;
		
		if ($secs <= 0) { $output = "now";
		}elseif ($secs > $second && $secs < $minute) { $output = round($secs/$second)." second";
		}elseif ($secs >= $minute && $secs < $hour) { $output = round($secs/$minute)." minute";
		}elseif ($secs >= $hour && $secs < $day) { $output = round($secs/$hour)." hour";
		}elseif ($secs >= $day && $secs < $week) { $output = round($secs/$day)." day";
		}elseif ($secs >= $week && $secs < $month) { $output = round($secs/$week)." week";
		}elseif ($secs >= $month && $secs < $year) { $output = round($secs/$month)." month";
		}elseif ($secs >= $year && $secs < $year*10) { $output = round($secs/$year)." year";
		}else{ $output = " more than a decade ago"; }
		
		if ($output <> "now"){
			$output = (substr($output,0,2)<>"1 ") ? $output."s" : $output;
		}
		return $output;
	}



echo relativedate(60); // 1 minute

Revision: 27463
at June 9, 2010 18:07 by LuckyShot


Initial Code
function relativedate($secs) {
	$second = 1;
	$minute = 60;
	$hour = 60*60;
	$day = 60*60*24;
	$week = 60*60*24*7;
	$month = 60*60*24*7*30;
	$year = 60*60*24*7*30*365;
	
	if ($secs <= 0) { $output = "now";
	}elseif ($secs > $second && $secs < $minute) { $output = round($secs/$second)." second";
	}elseif ($secs >= $minute && $secs < $hour) { $output = round($secs/$minute)." minute";
	}elseif ($secs >= $hour && $secs < $day) { $output = round($secs/$hour)." hour";
	}elseif ($secs >= $day && $secs < $week) { $output = round($secs/$day)." day";
	}elseif ($secs >= $week && $secs < $month) { $output = round($secs/$week)." week";
	}elseif ($secs >= $month && $secs < $year) { $output = round($secs/$month)." month";
	}elseif ($secs >= $year && $secs < $year*10) { $output = round($secs/$year)." year";
	}else{ $output = " more than a decade ago"; }
	
	if ($output <> "now"){
		$output = (substr($output,0,2)=="1 ") ? $output." ago" : $output."s ago";
	}
	return $output;
}


if (isset($_GET['secs'])) {echo relativedate($_GET['secs']);}

Initial URL
http://xaviesteve.com/category/web-design/php/

Initial Description
Gets seconds and returns it like Facebook/Twitter style: "2 minutes ago", "9 hours ago", etc...
The script actually returns "1 minute", "17 days"... so that you can customize it: "3 seconds ago", "in 1 minute", "will take 4 days", etc.

Initial Title
PHP - Relative date function (2 minutes ago, 3 days ago...)

Initial Tags
php, date

Initial Language
PHP