Development

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;
}

 

Share

Recent Posts

Kennington reservoir drained drone images

A drained and empty Kennington reservoir images from a drone in early July 2024. The…

1 year ago

Merrimu Reservoir drone images

Merrimu Reservoir from drone. Click images to view larger.

1 year ago

FTP getting array of file details such as size using PHP

Using FTP and PHP to get an array of file details such as size and…

2 years ago

Creating Laravel form requests

Creating and using Laravel form requests to create cleaner code, separation and reusability for your…

2 years ago

Improving the default Laravel login and register views

Improving the default Laravel login and register views in such a simple manner but making…

2 years ago

Laravel validation for checking if value exists in the database

Laravel validation for checking if a field value exists in the database. The validation rule…

2 years ago