PHP function to display time ago base on timestamp

Timestamp in PHP only for system usage, for user we have to show it in easy to read way like: 1 minutes ago, 1 hour ago … Today I will show you to use PHP function to display time ago base on timestamp.

php function time agoHere is very simple PHP function what you can use in any PHP project to display time.

<?php
function timeAgo($time_ago){
$cur_time 	= time();
$time_elapsed 	= $cur_time - $time_ago;
$seconds 	= $time_elapsed ;
$minutes 	= round($time_elapsed / 60 );
$hours 		= round($time_elapsed / 3600);
$days 		= round($time_elapsed / 86400 );
$weeks 		= round($time_elapsed / 604800);
$months 	= round($time_elapsed / 2600640 );
$years 		= round($time_elapsed / 31207680 );
// Seconds
if($seconds <= 60){
	echo "$seconds seconds ago";
}
//Minutes
else if($minutes <=60){
	if($minutes==1){
		echo "one minute ago";
	}
	else{
		echo "$minutes minutes ago";
	}
}
//Hours
else if($hours <=24){
	if($hours==1){
		echo "an hour ago";
	}else{
		echo "$hours hours ago";
	}
}
//Days
else if($days <= 7){
	if($days==1){
		echo "yesterday";
	}else{
		echo "$days days ago";
	}
}
//Weeks
else if($weeks <= 4.3){
	if($weeks==1){
		echo "a week ago";
	}else{
		echo "$weeks weeks ago";
	}
}
//Months
else if($months <=12){
	if($months==1){
		echo "a month ago";
	}else{
		echo "$months months ago";
	}
}
//Years
else{
	if($years==1){
		echo "one year ago";
	}else{
		echo "$years years ago";
	}
}
}

?>

Now, time to show and use it ‘s quite simple like this

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

You will see the output like this

one year ago

 

 

2 comments

  1. It work nice for me. But I want something a little different. Just look like this in output
    “about 1 hour ago”
    How can I customize your function?

  2. This is really helpful function, thanks to share with us 🙂
    I also recently wrote another PHP time ago function, where i fixed 1 minutes issue into minute hope this also help.
    https://htmlcssphptutorial.wordpress.com/2015/08/21/time-ago-php-function/

CDN by MaxCDN