Created
February 15, 2019 18:11
-
-
Save relliv/68291ba5d201c761877f7e48ad6be75d to your computer and use it in GitHub Desktop.
Human Readable Time String with PHP
This file contains hidden or 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 | |
/** | |
* Get time elapsed string from given between dates by human readable format | |
* | |
* @param string $date_now: current date | |
* @param string $date_old: target old date | |
* @param bool $full: need full date ago string | |
* | |
* @see source: https://stackoverflow.com/a/18602474 | |
* | |
* @return array|bool | |
*/ | |
function timeElapsed($date_now, $date_old) | |
{ | |
$old = new DateTime($date_old); | |
$now = new DateTime($date_now); | |
$diff = $now->diff($old); | |
$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 $k => &$v) { | |
if ($diff->$k) { | |
$v = $diff->$k . ',' . $v . ($diff->$k > 1 ? 's' : ''); | |
} else { | |
unset($string[$k]); | |
} | |
} | |
if ($string && is_array($string) && count($string) > 0) { | |
$parse_ago = explode(',', $string[key(array_slice($string, 0, 1))]); | |
return [ | |
'count' => $parse_ago[0], | |
'time_part' => $parse_ago[1], | |
]; | |
} else { | |
return [ | |
'count' => false, | |
'time_part' => 'just_now', | |
]; | |
} | |
return false; | |
} | |
// returns only one unit, x years, 5 months, 1 day | |
print_r(timeElapsed(date('Y-m-d H:i:s', time()), '2012-12-12 12:12:12')); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment