Output Is in Seconds. Convert to Hh:Mm:Ss Format in PHP

Output is in seconds. convert to hh:mm:ss format in php

1)

function foo($seconds) {
$t = round($seconds);
return sprintf('%02d:%02d:%02d', ($t/3600),($t/60%60), $t%60);
}

echo foo('290.52262423327'), "\n";
echo foo('9290.52262423327'), "\n";
echo foo(86400+120+6), "\n";

prints

00:04:51
02:34:51
24:02:06

2)

echo round($time, 2);

converting seconds to HH:MM:SS in PHP

Where is the 120 coming from? 142 (or 142.000) seconds equals 2 minutes 36 seconds (142 / 60)

142 / 60 = 2.36666667 minutes which doesn't equals 2min 36sec. 2.36666 is a decimal number, and it represents minutes. If you wish to format 2.36666 to minutes and seconds, then take the whole number as minutes, and 0.366666 * 60 as seconds, that is 22, so result is 2min 22sec.


You should cast 2nd parameter to integer, or at least remove :000 part:

$result['s'] = '142:000';
echo gmdate("H:i:s", (int)$result['s']); # 0:02:22

demo

You will have problem, if you have more than 86400 seconds (1 day). In that case you can use this.

Convert time in HH:MM:SS format to seconds only?

No need to explode anything:

$str_time = "23:12:95";

$str_time = preg_replace("/^([\d]{1,2})\:([\d]{2})$/", "00:$1:$2", $str_time);

sscanf($str_time, "%d:%d:%d", $hours, $minutes, $seconds);

$time_seconds = $hours * 3600 + $minutes * 60 + $seconds;

And if you don't want to use regular expressions:

$str_time = "2:50";

sscanf($str_time, "%d:%d:%d", $hours, $minutes, $seconds);

$time_seconds = isset($seconds) ? $hours * 3600 + $minutes * 60 + $seconds : $hours * 60 + $minutes;

Convert seconds to Hour:Minute:Second

You can use the gmdate() function:

echo gmdate("H:i:s", 685);

output seconds in hh:mm:ss format relative to how many seconds

I will go with a minor modification of your code.
I believe your code is actually very fast since you use native functions.

Here goes

function format_time($t) {
$t = round($t);
return ($t < 3600 ? sprintf("%d:%02d", ($t/60%60), ($t%60)) :
sprintf("%d:%02d:%02d", ($t/3600),($t/60%60), ($t%60)));
}

Outputs are exactly as you specified in your question.
Cheers.

How to convert seconds to time format?

$hours = floor($seconds / 3600);
$mins = floor($seconds / 60 % 60);
$secs = floor($seconds % 60);

If you want to get time format:

$timeFormat = sprintf('%02d:%02d:%02d', $hours, $mins, $secs);

How to convert a HH:MM:SS string to seconds with PHP?

The quick way:

echo strtotime('01:00:00') - strtotime('TODAY'); // 3600


Related Topics



Leave a reply



Submit