We have seen on social media platforms that if someone posts something, the time is given below that post, such as 5 minutes ago or 2 days ago. In today’s tutorial, I will show you how to convert timestamp to time ago in PHP.
Now we need to make a custom function for that. For example, we will create a function i.e time_ago()
. The function will take a valid date and time format.
CONTENTS
Function:
function time_ago($datetime, $full = false) {
$input_date = new DateTime($datetime); //store supplied valid date and time
$now = new DateTime; //store current date and time
$date_diff = $now->diff($input_date);
$date_diff->w = floor($date_diff->d / 7);
$date_diff->d -= $date_diff->w * 7;
$date_array = array(
'y' => 'year',
'm' => 'month',
'w' => 'week',
'd' => 'day',
'h' => 'hour',
'i' => 'minute',
's' => 'second',
);
foreach ($date_array as $k => &$v) {
if ($date_diff->$k) {
$v = $date_diff->$k . ' ' . $v . ($date_diff->$k > 1 ? 's' : '');
} else {
unset($date_array[$k]);
}
}
if (!$full) {
$date_array = array_slice($date_array, 0, 1);
}
return $date_array ? implode(', ', $date_array) . ' ago' : 'just now';
}
How to use?
echo time_ago('2021-07-05 22:02:35'); //datetime format
echo time_ago('@1625502817'); // timestamp input
echo time_ago('2021-07-05 22:02:35', true); //datetime format with full date
Result:
5 hours ago
1 minute ago
5 hours, 27 minutes, 14 seconds ago