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
<?php
function timeAgo($datetime, $full = false) {
    $now = new DateTime;
    $ago = new DateTime($datetime);
    $diff = $now->diff($ago);

    $diff->w = floor($diff->d / 7);
    $diff->d -= $diff->w * 7;

    $string = array(
        'y' => 'year',
        'm' => 'month',
        'w' => 'week',
        'd' => 'day',
        'h' => 'hour',
        'i' => 'minute',
        's' => 'second',
    );
    foreach ($string as $key => &$val) {
        if ($diff->$key) {
            $val = $diff->$key . ' ' . $val . ($diff->$key > 1 ? 's' : '');
        } else {
            unset($string[$key]);
        }
    }

    if (!$full){
        $string = array_slice($string, 0, 1);
    } 
    return $string ? implode(', ', $string) . ' ago' : 'just now';
}
?>

Usage PHP Time Ago Function

PHP
<?php

echo timeAgo('2020-04-19 11:38:43'); 
// 4 months

echo timeAgo('2020-04-19 11:38:43', true); 
//4 months, 1 week, 4 days, 23 hours, 5 minutes, 19 seconds

echo timeAgo('2010-10-20'); // 9 years

echo timeAgo('2010-10-20', true); 
//9 years, 10 months, 1 week, 4 days, 10 hours, 45 minutes, 32 seconds

//timestamp 
echo timeAgo('@1598867187'); // 19 seconds

echo timeAgo('@1598867187', true); //19 seconds

// html
$join_date = '2020-04-19 11:38:43';
echo '<div title="'.$join_date.'">'.timeAgo($join_date).'</div>';

?>