Skip to content

Instantly share code, notes, and snippets.

@jersonmartinez
Forked from james2doyle/elapsed-time.php
Created February 9, 2020 16:45
Show Gist options
  • Save jersonmartinez/9ccc8e1fa369998589d28f897040522b to your computer and use it in GitHub Desktop.
Save jersonmartinez/9ccc8e1fa369998589d28f897040522b to your computer and use it in GitHub Desktop.
PHP elapsed time function which takes in a timestamp and spits out a "timeago" sentence.
<?php
function elapsed_time($timestamp, $precision = 2) {
$time = time() - $timestamp;
$a = array('decade' => 315576000, 'year' => 31557600, 'month' => 2629800, 'week' => 604800, 'day' => 86400, 'hour' => 3600, 'min' => 60, 'sec' => 1);
$i = 0;
foreach($a as $k => $v) {
$$k = floor($time/$v);
if ($$k) $i++;
$time = $i >= $precision ? 0 : $time - $$k * $v;
$s = $$k > 1 ? 's' : '';
$$k = $$k ? $$k.' '.$k.$s.' ' : '';
@$result .= $$k;
}
return $result ? $result.'ago' : '1 sec to go';
}
echo elapsed_time('1234567890').'<br />'; // 3 years 5 months ago
echo elapsed_time('1234567890', 6); // 3 years 5 months 1 week 2 days 57 mins 4 secs ago
?>
@jersonmartinez
Copy link
Author

jersonmartinez commented Feb 9, 2020

In spanish:

public function getElapsedTime($timestamp, $precision = 2) {
	$time = time() - $timestamp;
			
	$a = array(
		'década' 	=> 315576000, 
		'año' 		=> 31557600, 
		'mes' 		=> 2629800, 
		'semana' 	=> 604800, 
		'día' 		=> 86400, 
		'hora' 		=> 3600, 
		'min' 		=> 60, 
		'seg' 		=> 1
	);
			
	$i = 0;
			
	foreach ($a as $k => $v) {
		$$k = floor($time/$v);
			
		if ($$k) $i++;
				
		$time = $i >= $precision ? 0 : $time - $$k * $v;
		$s = $$k > 1 ? 's' : '';
		$$k = $$k ? $$k.' '.$k.$s.' ' : '';
		@$result .= $$k;
	}

	$result = trim($result);

	$result = str_replace('mess ', 'meses ', $result);
	$result = str_replace('a ', 'a y ', $result);
	$result = str_replace('s ', 's y ', $result);

	return $result ? 'Hace '.$result : 'Hace un momento';
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment