Convert seconds to hours, minutes and seconds (PHP)
Here is a small function that converts number of seconds to an array containing hours, minutes and seconds separately.
- <?php
- /**
- * Convert number of seconds into hours, minutes and seconds
- * and return an array containing those values
- *
- * @param integer $seconds Number of seconds to parse
- * @return array
- */
- function secondsToTime($seconds)
- {
- // extract hours
- $hours = floor($seconds / (60 * 60));
- // extract minutes
- $divisor_for_minutes = $seconds % (60 * 60);
- $minutes = floor($divisor_for_minutes / 60);
- // extract the remaining seconds
- $divisor_for_seconds = $divisor_for_minutes % 60;
- $seconds = ceil($divisor_for_seconds);
- // return the final array
- $obj = array(
- "h" => (int) $hours,
- "m" => (int) $minutes,
- "s" => (int) $seconds,
- );
- return $obj;
- }
The first thing we need to do is get the number of hours. To do that we divide $seconds by 3600 (number of seconds in one hour) and use only the whole number of the result.
For example, if the supplied time was 4572 seconds then the result of the division would be 1, because 4572 / 3600 is 1.27, which means that there is only one full hour in 4572 seconds.
Next step is to find out the number of minutes in the remaining time. This is done by dividing the total number of seconds with number of seconds in $hours and using only the remainder (please see {php:operators.arithmetic} section in PHP manual for more information on the modulus operator). Then we do the same thing as we did with $hours, except with minutes - we divide the remaining number of seconds with 60 and use only the whole number.
Let use the same number of seconds for an example - 4572. The $divisor_for_minutes will be 900 because 4500 % 3600 is 972 (you can only fit 3600 inside 4572 once and after doing that the remaining number is 972).
The last step in our calculations is getting the seconds part of the time. This is pretty easy as we do exactly the same thing as we did with minutes except now, but instead we do the modulus division with 60 and not with 3600.
In our example case, $divisor_for_seconds (number of seconds in minutes and seconds) will be 972 % 60 = 12 (you can fit 60 inside 972 sixteen full times (60 * 16 = 960) and the remainder afterwards is 12). And this is our seconds part.
I think the rest is clear and doesn't need any explanation.
As always - any comments and/or suggestions will be welcome. ;)
NOTE: a JavaScript implementation is also available for this function. You can find it here: Convert seconds to hours, minutes and seconds (JavaScript).



Why reinvent the wheel? gmdate ('H:i:s', $seconds);