Skip to content

Instantly share code, notes, and snippets.

@adamli
Last active August 29, 2015 14:08
Show Gist options
  • Select an option

  • Save adamli/784dea9767492e9330aa to your computer and use it in GitHub Desktop.

Select an option

Save adamli/784dea9767492e9330aa to your computer and use it in GitHub Desktop.
Function for formatting time difference in a human friendly format (e.g. 4h 12m)
<?php
echo time_elapsed(35); // will output 35s
echo time_elapsed(2*60 + 15); // will output 2m
echo time_elapsed(2*60 + 15, TRUE); // will output 2m 15s
echo time_elapsed(2*60*60 + 15*60); // will output 2h 15m
echo time_elapsed(2*24*60*60 + 15*60*60); // will output 2d 15h
echo time_elapsed(2*24*60*60 + 15*60*60 + 3*60); // will output 2d 15h 3m
echo time_elapsed(5*7*24*60*60 + 2*24*60*60 + 15*60*60 + 3*60); // will output 5w 2d 15h 3m
function time_elapsed($seconds_difference, $show_seconds_in_result = FALSE){
$bit = array(
'year' => $seconds_difference / 31556926 % 12,
'w' => $seconds_difference / 604800 % 52,
'd' => $seconds_difference / 86400 % 7,
'h' => $seconds_difference / 3600 % 24,
'm' => $seconds_difference / 60 % 60,
);
if ($show_seconds_in_result || $seconds_difference < 60)
$bit['s'] = $seconds_difference % 60;
$ret = array();
foreach($bit as $k => $v){
if($v >= 1)
$ret[] = $v . $k;
}
return join(' ', $ret);
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment