Convert seconds to days, hours, minutes, seconds in PHP

With the following function you can easily convert an integer containing seconds to a nice days, hours, minutes, seconds string or array.

function secondsToTime($seconds, $return_type="string") { // extract days $days = floor($seconds / 3600 / 24); // extract hours $hours = floor($seconds / 3600) - $days*24; // extract minutes $divisor_for_minutes = $seconds % 3600; $minutes = floor($divisor_for_minutes / 60); // extract the remaining seconds $divisor_for_seconds = $divisor_for_minutes % 60; $seconds = ceil($divisor_for_seconds); // return the final array $obj = array( "d" => (int) $days, "h" => (int) $hours, "m" => (int) $minutes, "s" => (int) $seconds ); $str = ""; if ($obj["d"]!=0) $str .= $obj["d"]."d "; $str .= $obj["h"]."h "; $str .= $obj["m"]."m "; if ($return_type=="string") return $obj["d"]." days, ".$obj["m"]." minutes, ".$obj["h"]." hours, ".$obj["s"]." seconds"; else return $obj; }
Code language: PHP (php)

To use the above function you can either use the default return type and call it like so:

echo secondsToTime(478641);
Code language: PHP (php)

..which gives the following result:

5 days, 57 minutes, 12 hours, 21 seconds

..or you can specify to return the data as an array for later manipulation:

print_r(secondsToTime(478641, "array"));
Code language: JavaScript (javascript)

..which gives the following result:

Array ( [d] => 5 [h] => 12 [m] => 57 [s] => 21 )
Code language: PHP (php)
Tags:
Subscribe
Notify of
guest
2 Comments
Newest
Oldest Most Voted
Inline Feedbacks
View all comments
Esteban Gamboa Arrieta

Freaking great code my friend!

zinzinzibidi
9 years ago

great code! thank you!