Skip to content

Instantly share code, notes, and snippets.

@Vyygir
Forked from zachstronaut/gist:1184831
Last active February 10, 2017 10:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Vyygir/5a70d8007141cf49541b967c8e9a2280 to your computer and use it in GitHub Desktop.
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
<?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