1

I want to convert seconds into seconds, minutes, then hours, and anything longer than 24 hours should include the total number of hours. Currently I have

function secondsToTime($seconds) {
    $dtF = new DateTime("@0");
    $dtT = new DateTime("@$seconds");
    return $dtF->diff($dtT)->format('%hH %iM %ss');
}

But when I use

secondsToTime(90000)

I get:

1H 00M 00S

Instead, it should say

25H 00M 00S

I understand that it is technically correct, but how do I get days/weeks/months to convert into hours?

  • Just multiply all days by 24 and you get them in hours; See; http://php.net/manual/en/class.dateinterval.php#dateinterval.props.days – Rizier123 May 01 '16 at 16:29
  • Divide $seconds by 3600 and round down. – Barmar May 01 '16 at 16:30
  • Possible duplicate of [Convert seconds to Hour:Minute:Second](http://stackoverflow.com/questions/3172332/convert-seconds-to-hourminutesecond) – splash58 May 01 '16 at 16:37

1 Answers1

5

You don't need to use DateTime, just simple arithmetic.

$h = floor($seconds / 3600);
$m = floor(($seconds % 3600) / 60);
$s = $seconds % 60;
return sprintf("%dH %02dM %02dS", $h, $m, $s);
Barmar
  • 741,623
  • 53
  • 500
  • 612