Last active
August 29, 2015 14:08
-
-
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)
This file contains hidden or 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 | |
| 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