How to convert seconds to Hour:Minute:Second in PHP
In this article we will see how can you convert seconds to Hour:Minute:Second format in PHP both using gmdate() function and without using gmdate() function .
gmdate() basically a php function that allow you to convert seconds into H:M:S format but there is problem with gmdate() method that it only ranges from 00:00:00 to 23:59:59 , if total seconds exceeding more than 23:59:59 then it will again starts from 00:00:00 . So here we will se both cases of converting seconds into Hour:Minute:Second both using and without using gmdate() method .
gmdate() method basically takes two parameter first one is the conversion format and another is seconds .
gmdate(format, seconds);
gmdate("H:i:s", 3600);
Using gmdate() method :
public function convert_seconds_to_hours_minutes_seconds()
{
$initial_time =86399;
return gmdate("H:i:s", $initial_time);
}
Output :
23:59:59
Without using gmdate() method :
public function convert_seconds_to_hours_minutes_seconds()
{
$initial_time =3656;
$hours = floor($initial_time / 3600);
$minutes = floor(($initial_time / 60) % 60);
$seconds = $initial_time % 60;
if($hours<10)
{
$hours = sprintf('%02d', $hours);
}
if($minutes<10)
{
$minutes = sprintf('%02d', $minutes);
}
if($seconds<10)
{
$seconds = sprintf('%02d', $seconds);
}
$final_time = $hours.":".$minutes.":".$seconds;
return $final_time;
}
Output :
01:00:56
sprintf() is a php method basically used to add preceding zero's on a digit .
Thank you for reading this article 😊
For any query do not hesitate to comment 💬
