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 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;
} Â
A drained and empty Kennington reservoir images from a drone in early July 2024. The…
Merrimu Reservoir from drone. Click images to view larger.
Some early September spring shots from a bushwalk, It is still too early for wildflowers.
I recently needed to clone over a smaller NVMe to a 2TB SK Hynix Platinum…
If you ever needed a simple solution in Laravel to delete an entire directory and…
How to enforce only one user to register or be registered in a Laravel web…