PHP Time Ago Function

Time Ago PHP Function. PHP Facebook style time ago function

DateTime convert Time Ago
Just now
1 minut ago
1 week ago
1 month ago
1 year ago
function
<?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
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
?>
<?php
$join_date = '2020-04-19 11:38:43';
echo '<div title="'.$join_date.'">'.timeAgo($join_date).'</div>';
?>