new time ago

Time Ago PHP function for showing post time

Posted on Posted in PHP, Technology

php-time-ago-fitnessNit
php-time-ago-fitnessNit

Sometimes we need to show the publish post time like(1 hr ago, 1 week ago etc). I have created below function for this need.

<?
function time_passed($date) {
	$dateTime    = '';
	$start_date  = new DateTime($date);
	$since_start = $start_date->diff(new DateTime(date('Y-m-d H:i:s')));
	if ($since_start->y != 0) {
		$dateTime = $since_start->y.' year ago';
	} else if ($since_start->m != 0) {
		$dateTime = $since_start->m.' month ago';
	} else if ($since_start->d != 0) {
		$dateTime = $since_start->d.' day ago';
	} else if ($since_start->h != 0) {
		$dateTime = $since_start->h.' hr ago';
	} else if ($since_start->i != 0) {
		$dateTime = $since_start->i.' m ago';
	} else {
		$dateTime = $dateTime.'Just now';
	}
	return $dateTime;
}
?>

Function call :

<?php
$curenttime="2013-07-10 09:09:09";
echo time_passed($curenttime); 
?>


Let me know if you need any help or provide your feedback by comment below.