Search code examples
phptimedate-conversion

How to convert given seconds to hours minutes seconds format in php in custom way?


I will get random number of seconds the number may greater than 86400 which is greater than 24hours (when converts to hours) so php gmdate() won't get my required output. So I created the following code.

$ts = mt_rand(36000,99999); 
echo floor($ts/3600)."Hr ".floor(($ts/3600 - floor($ts/3600))*60)."min ".round(((($ts/3600 - floor($ts/3600))*60) - floor(($ts/3600 - floor($ts/3600))*60))*60)."sec";

I am getting the output like 22Hr 29min 4sec for $ts = 80944;
Everything is fine but for $ts = 39540; the output came is 10Hr 58min 60sec here 60sec came which is wrong. it should get like 10Hr 59min 0sec. What's wrong in my code?


Solution

  • I didn't break your code apart to find out what was wrong, but I believe this solves the problem.

    $ts = mt_rand(36000,99999);
    
    $h = floor($ts / 3600);
    $m = floor(($ts - 3600 * $h) / 60);
    $s = $ts - ($h * 3600) - ($m * 60);
    
    echo $h . "Hr " . $m . "Min " . $s . "s";