PHP datetime to time ago string

A PHP function to convert a DateTime to a years, months, weeks, days, hours, minutes and seconds ago string.

An option can be passed through to have a short string that will default to the largest date format.

Example usage:

echo date('Y-m-d H:i:s');//2021-09-01 21:36:42

echo timeElapsedString('2021-08-01 20:07:20',true);//1 month, 1 hour, 29 minutes and 22 seconds


echo date('Y-m-d H:i:s');//2021-09-01 21:36:11

echo timeElapsedString('2021-08-01 20:07:20',false);//1 month

Gist link.

The function adapted from here:

<?php
function timeElapsedString(string $past_datetime, bool $full_string = true): string
{
    $now = new DateTime;
    $difference = $now->diff(new DateTime($past_datetime));
    $difference->w = floor($difference->d / 7);
    $difference->d -= ($difference->w * 7);
    $formats = array(
        'y' => 'year',
        'm' => 'month',
        'w' => 'week',
        'd' => 'day',
        'h' => 'hour',
        'i' => 'minute',
        's' => 'second'
    );
    foreach ($formats as $k => &$v) {
        if ($difference->$k) {
            $v = $difference->$k . ' ' . $v . ($difference->$k > 1 ? 's' : '');
        } else {
            unset($formats[$k]);
        }
    }
    if (!$full_string) {
        $formats = array_slice($formats, 0, 1);
    }
    $string = implode(', ', $formats);
    if (strrpos($string, ',')) {
        $string = substr_replace($string, ' and', strrpos($string, ','), strlen(','));
    }
    return $string;
}