-
-
Save Vyygir/5a70d8007141cf49541b967c8e9a2280 to your computer and use it in GitHub Desktop.
Get a relative time string in PHP without a lot of if/else or switch/case
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 | |
/** | |
* time_elapsed_string() | |
* | |
* @author Zachary Johnson | |
* @link http://www.zachstronaut.com/posts/2009/01/20/php-relative-date-time-string.html | |
* | |
* @author Vyygir | |
* @link https://gist.github.com/Vyygir/5a70d8007141cf49541b967c8e9a2280 | |
* @description I had to modify this slightly from the previous version, as it was causing errors | |
* in my environment, and I really just needed a quick solution for relative time. | |
*/ | |
function time_elapsed_string($ptime) { | |
$etime = time() - $ptime; | |
if ($etime < 1) { | |
return '0 seconds'; | |
} | |
$a = array(); | |
$a[12 * 30 * 24 * 60 * 60] = 'year'; | |
$a[30 * 24 * 60 * 60] = 'month'; | |
$a[24 * 60 * 60] = 'day'; | |
$a[60 * 60] = 'hour'; | |
$a[60] = 'minute'; | |
$a[1] = 'second'; | |
foreach ($a as $secs => $str) { | |
$d = $etime / $secs; | |
if ($d >= 1) { | |
$r = round($d); | |
return sprintf('%s %s%s', $r, $str, ($r > 1 ? 's' : '')); | |
} | |
} | |
return false; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment