PHP Facebook Time Ago Display

It is a good idea to show your visitor the exact comment, post, chat, message, etc. about it dates, especially exactly how low they are untill current time. Showing such this detail date information, your website will be more professional and attractive regarding to this clear and accurate date information.

You may have much experiences with facebook social network where date time ago is very common and attractive. This function will calculate the datetime passed by display the accurate date and time passed with short description text (ex. just now, a few seconds ago, 10 seconds ago, 1 minute ago, 1 hour ago, 1 day ago, etc.).

You can also change the text label to be displayed directly in the function and add some more condition as your need. The bellow instruction will show you the function script and assist you to use the function correctly.

INSTRUCTION

You can use this function in the external file that need to be included to your working file or directly in your working file.

function dateTimeAgo($datetimeString){
$start_date = new DateTime($datetimeString);
$now_datetime = new DateTime(date("Y-m-d H:i:s"));
										
$recieved_date = date_format(date_create($datetimeString),'d/m/Y g:i:s A');	
										
$interval = $start_date->diff($now_datetime);
$year_ago = $interval->y;$month_ago = $interval->m;$day_ago = $interval->d;$hour_ago = $interval->h;$minute_ago = $interval->i;$second_ago = $interval->s;										
$datetime_ago = '';
										
if($year_ago==0 and $month_ago==0 and $day_ago==0 and $hour_ago==0 and $minute_ago==0){
$datetime_ago = ($second_ago<=1?"":(($second_ago>1 and $second_ago<4)?" a few":$second_ago)).($second_ago<=1?" just now":" seconds ago");
}elseif($year_ago==0 and $month_ago==0 and $day_ago==0 and $hour_ago==0){
$datetime_ago = $minute_ago.($minute_ago>1?" minutes ago":" minute ago");
}elseif($year_ago==0 and $month_ago==0 and $day_ago==0){
$datetime_ago = $hour_ago.($hour_ago>1?" hours ago":" hour ago");
}elseif($year_ago==0 and $month_ago==0){
$datetime_ago = $day_ago.($day_ago>1?" days ago":" day ago");
}else{
$datetime_ago = $recieved_date;
}
return $datetime_ago;		
}

This function will return the passed datetime string with the short description string. To use this function, you just input the datetime string to the function. If your retrieve datetime data from your database, you just use the returned datetime from your database to this function.

//suppose current datetime is : 2014-07-25 13:14:30
echo dateTimeAgo('2014-07-25 13:10:00');
//this will return: 4 minutes ago

Please make sure that working with datetime function, you may need to check your default timezone to aviod wrong datetime display and other confusion.

 

Similar Tutorials

Comments