Other solutions use gmdate, but fail in edge cases where you have more than 86400 seconds. To get around this, we can simply compute the number of hours ourselves, then let gmdate compute the remaining seconds into minutes/seconds.
This code avoids as much as possible of the tedious function calls and piece-by-piece string-building, and the big and bulky functions people are making for this.
It produces "1h05m00s" format and uses leading zeroes for minutes and seconds, as long as another non-zero time component precedes them.
And it skips all empty leading components to avoid giving you useless info like "0h00m01s" (instead that will show up as "1s").
Example results: "1s", "1m00s", "19m08s", "1h00m00s", "4h08m39s".
If you want to make the code even shorter (but less readable), you can avoid the $converted array and instead put the values directly in the sprintf() call, as follows:
Duration must be 0 or higher in both of the code pieces above. Negative durations are not supported. But you can handle negative durations by using the following alternative code instead:
Other solutions use
gmdate
, but fail in edge cases where you have more than 86400 seconds. To get around this, we can simply compute the number of hours ourselves, then letgmdate
compute the remaining seconds into minutes/seconds.Input:
6030
Output:1:40:30
Input:
2000006030
Output:555557:13:50
See:
From: Convert seconds into days, hours, minutes and seconds
You can use the
gmdate()
function:Use function
gmdate()
only if seconds are less than86400
(1 day) :See: gmdate()
Run the Demo
Convert seconds to format by 'foot' no limit* :
See: floor(), sprintf(), arithmetic operators
Run the Demo
Example use of
DateTime
extension:See: DateTime::__construct(), DateTime::modify(), clone, sprintf()
Run the Demo
MySQL example range of the result is constrained to that of the TIME data type, which is from
-838:59:59
to838:59:59
:See: SEC_TO_TIME
Run the Demo
PostgreSQL example:
Run the Demo
Solution from: https://gist.github.com/SteveJobzniak/c91a8e2426bac5cb9b0cbc1bdbc45e4b
Here is a very clean and short method!
This code avoids as much as possible of the tedious function calls and piece-by-piece string-building, and the big and bulky functions people are making for this.
It produces "1h05m00s" format and uses leading zeroes for minutes and seconds, as long as another non-zero time component precedes them.
And it skips all empty leading components to avoid giving you useless info like "0h00m01s" (instead that will show up as "1s").
Example results: "1s", "1m00s", "19m08s", "1h00m00s", "4h08m39s".
If you want to make the code even shorter (but less readable), you can avoid the
$converted
array and instead put the values directly in the sprintf() call, as follows:Duration must be 0 or higher in both of the code pieces above. Negative durations are not supported. But you can handle negative durations by using the following alternative code instead: