is there a built in functionality in php to convert seconds to hh:mm:ss
Asked
Active
Viewed 560 times
4
-
None that I know of. There are simple code snippets out there though for this. Google "php seconds to hh mm ss". First result – simshaun Jan 06 '11 at 16:26
-
seconds?? do you mean timestamp?? – shankhan Jan 06 '11 at 16:26
-
@simshaun - I know - thanks, that's why I asked for built in. @shankhan - seconds, not time stamps – Itay Moav -Malimovka Jan 06 '11 at 16:29
-
? why the down votes? who and how I offended with this question? – Itay Moav -Malimovka Jan 06 '11 at 17:00
4 Answers
3
There's no built in function, this will work though:
function formatSeconds($seconds){
$hours = $seconds / (60 * 60);
$minutes = ( $seconds - $hours * 60 * 60) / 60;
$seconds = $seconds - $hours * 60 * 60 - $minutes * 60 - $seconds;
return $hours.':'.$minutes.':'.$seconds;
}

fredley
- 32,953
- 42
- 145
- 236
-
-
2To prefix zeros you may also use `sprintf()`. `return sprintf('%02d:%02d:%02d', $hours, $minutes, $seconds);` – Amil Waduwawara Jan 06 '11 at 16:37
-
0
$seconds=3672;
echo date_create()->add(new DateInterval("PT{$seconds}S"))
->diff(new DateTime)
->format('%H:%I:%S');
Just another way that works.

Itay Moav -Malimovka
- 52,579
- 61
- 190
- 278
-1
I needed an answer to this recently and I ran across this web page concerning inserting a phpdate into a mysql table. (I bet this is also what you're dealing with.) It seems to indicate that you can use something like
$mysqldate = date( 'H:i:s', time());
This seems to work fine even if the number of seconds exceeds a 24 hour period.

JnBrymn
- 24,245
- 28
- 105
- 147
-2