Skip to content

Instantly share code, notes, and snippets.

@zachstronaut
Created August 31, 2011 21:53
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save zachstronaut/1184831 to your computer and use it in GitHub Desktop.
Save zachstronaut/1184831 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
<?php
/**
* time_elapsed_string()
*
* Zachary Johnson
* http://www.zachstronaut.com/posts/2009/01/20/php-relative-date-time-string.html
*/
function time_elapsed_string($ptime) {
$etime = time() - $ptime;
if ($etime < 1) {
return '0 seconds';
}
$a = array( 12 * 30 * 24 * 60 * 60 => 'year',
30 * 24 * 60 * 60 => 'month',
24 * 60 * 60 => 'day',
60 * 60 => 'hour',
60 => 'minute',
1 => 'second'
);
foreach ($a as $secs => $str) {
$d = $etime / $secs;
if ($d >= 1) {
$r = round($d);
return $r . ' ' . $str . ($r > 1 ? 's' : '');
}
}
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment