Time Ago Implementation in PHP/LARAVEL
Table of contents
Original Post Url : https://www.w3schools.in/php/examples/time-ago-function
PHP Time Ago functionality is used to display time in a different format.
- Display the time format, which is easy to understand.
- Display the time format similar to different time zone.
- It is commonly used in messaging and feeds.
Time Ago Implementation
It takes the timestamp as input and subtracts it with the current timestamp. Then it compares the remaining date with a predefined set of rules which determine the month, day, minute, and even year. Then it calculates time difference by using a predefined set of rules which determine the second, minute, hour, day, month, and year.
Time Ago Function
function get_time_ago( $time )
{
$time_difference = time() - strtotime($time);
if( $time_difference < 1 ) { return 'less than 1 second ago'; }
$condition = array( 12 * 30 * 24 * 60 * 60 => 'year',
30 * 24 * 60 * 60 => 'month',
24 * 60 * 60 => 'day',
60 * 60 => 'hour',
60 => 'minute',
1 => 'second'
);
foreach( $condition as $secs => $str )
{
$d = $time_difference / $secs;
if( $d >= 1 )
{
$t = round( $d );
return 'about ' . $t . ' ' . $str . ( $t > 1 ? 's' : '' ) . ' ago';
}
}
}
Calling the Function
echo get_time_ago( time()-5 ).'<br>';
//about 5 seconds ago
echo get_time_ago( time()-60 ).'<br>';
//about 1 minute ago
echo get_time_ago( time()-3600 ).'<br>';
//about 1 hour ago
echo get_time_ago( time()-86400 ).'<br>';
//about 1 day ago
echo get_time_ago( time()-2592000 ).'<br>';
//about 1 month ago
echo get_time_ago( time()-31104000 ).'<br>';
//about 1 year ago
.
.
.
echo get_time_ago( strtotime("2013-12-01") );
//about 2 years ago