CurtisUpshall
CurtisUpshall

Reputation: 75

PHP Convert seconds into seconds, minutes, hours with hours exceeding 24

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?

Upvotes: 1

Views: 774

Answers (1)

Barmar
Barmar

Reputation: 780889

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);

Upvotes: 5

Related Questions