Last active
September 1, 2021 10:40
-
-
Save cp6/79252c3decf9f794ab24512496309862 to your computer and use it in GitHub Desktop.
PHP years, months, weeks, days, hours, minutes and seconds past a date time
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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; | |
} | |
echo date('Y-m-d H:i:s');//2021-09-01 20:18:46 | |
echo timeElapsedString('2021-08-01 20:07:20');//1 month, 11 minutes and 26 seconds |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment