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.

Download  Run Code

 
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.

Download  Run Code

 
A simple mathematical calculation can also be used to divide the given seconds into hour-minute-second intervals, as shown below:

Download  Run Code

That’s all there is to converting seconds in PHP to hour-minute-second.