Convert seconds to hours-minutes-seconds in PHP
This article demonstrates how to convert seconds into hours-minutes-seconds in PHP.
1. Using gmdate() function
With the gmdate() function, you can easily split the given seconds into hour-minute-second intervals. It takes the format of the outputted date string and the optional timestamp parameter, in that order. The idea is to pass the format H:i:s in the date string parameter and the number of seconds in the timestamp parameter.
|
1 2 3 4 |
<?php $seconds = 3675; echo gmdate("H:i:s", $seconds); // 01:01:15 ?> |
Here, H represents the hours in 24-hour format (00 through 23), i represents the minutes (00 to 59), and s represents the seconds (00 through 59), all with leading zeros. However, this only works if the number of seconds is less than 86400, i.e., 1 day (60 x 60 x 24).
2. Using DateTime::diff() function
The idea is to construct a DateTime object using localized notations, with "@" representing the Unix timestamp, and get its difference with Epoch time using the DateTime::diff() function. Then you can extract the number of hours, minutes, and seconds information from the resultant DateInterval object using its h, i, and s properties, respectively.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
<?php $seconds = 43675; $start = new DateTime("@0"); $end = new DateTime("@$seconds"); $interval = $start->diff($end); $H = $interval->days * 24 + $interval->h; $i = $interval->i; $s = $interval->s; echo sprintf("%02d:%02d:%02d", $H, $i, $s); // 12:07:55 ?> |
A simple mathematical calculation can also be used to divide the given seconds into hour-minute-second intervals, as shown below:
|
1 2 3 4 5 6 7 8 9 |
<?php $seconds = 43675; $H = floor($seconds / 3600); $i = floor(($seconds / 60) % 60); $s = $seconds % 60; echo sprintf("%02d:%02d:%02d", $H, $i, $s); // 12:07:55 ?> |
That’s all there is to converting seconds in PHP to hour-minute-second.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)