PHP Time Ago Function
Converting timestamp to time ago Using PHP function. Times Converting To Hour Day Month And Year, PHP Datetime to time ago, just now, 1 day, 1 month, 1 year ago, Facebook-style time ago function using PHP
DateTime convert Time Ago
Just now
1 minute ago
1 week ago
1 month ago
1 year ago
PHP Function TimeAgo
<?php
function time_ago($datetime, $full = false) {
$now = new DateTime();
$ago = new DateTime($datetime);
$diff = $now->diff($ago);
$ar = [];
foreach ($diff as $key => $value) {
$ar[$key] = $value;
}
$x = floor($diff->d / 7);
$ar['w'] = $x;
$ar['d'] -= $x * 7;
$d_string = [
'y' => 'year',
'm' => 'month',
'w' => 'week',
'd' => 'day',
'h' => 'hour',
'i' => 'minute',
's' => 'second',
];
foreach ($d_string as $key => &$val) {
if ($ar[$key]) {
$val = $ar[$key] . ' ' . $val . ($ar[$key] > 1 ? 's' : '');
} else {
unset($d_string[$key]);
}
}
if (!$full) {
$d_string = array_slice($d_string, 0, 1);
}
return $d_string ? implode(', ', $d_string) . ' ago' : 'just now';
}
?>
Usage PHP Time Ago Function
<?php
echo time_ago('2020-04-19 11:38:43');
// 4 months
echo time_ago('2020-04-19 11:38:43', true);
//4 months, 1 week, 4 days, 23 hours, 5 minutes, 19 seconds
echo time_ago('2010-10-20'); // 9 years
echo time_ago('2010-10-20', true);
//9 years, 10 months, 1 week, 4 days, 10 hours, 45 minutes, 32 seconds
//timestamp
echo time_ago('@1598867187'); // 19 seconds
echo time_ago('@1598867187', true); //19 seconds
// html
$join_date = '2020-04-19 11:38:43';
echo '<div title="'.$join_date.'">'.time_ago($join_date).'</div>';
?>