Convert Seconds To Hours, Minutes in PHP

Read {count} times since 2020

Say you’re running a process that runs in the background. It’s better to not let the user lose their patience and tell them when it will finish. But, you have the time remaining in seconds. If we show the user :

567 seconds to complete

He/she (user) would have to take a calculator and convert it into minutes or hours. Or if the guy/gal is not a math genius, he would close the UI and say "What the Hell ?"

The primary point in UI is that

Don't irritate the user

Mark my words : "You shouldn’t make the user angry".

Seconds is converted to Hours, Minutes

Here is a simple function to convert seconds to hours, minutes and seconds separately or mixed together :

function secToHR($seconds) {
  $hours = floor($seconds / 3600);
  $minutes = floor(($seconds / 60) % 60);
  $seconds = $seconds % 60;
  return "$hours:$minutes:$seconds";

If you’re wondering why I chose secToHR as the function name, it’s the abbreviation of Seconds to Human Readable.

Or if you wanna display like this :

1 hour, 20 minutes remaining
10 minutes, 20 seconds remaining
15 seconds remaining

then, replace the return function with this :

return $hours > 0 ? "$hours hours, $minutes minutes remaining" : ($minutes > 0 ? "$minutes minutes, $seconds seconds remaining" : "$seconds seconds remaining");

BTW, I would suggest you do it like above ^, because it’s more user friendly.


Simple as it is :

 * Function with 'h:m:s' form as return value
echo secToHR(560);
echo secToHR(10950);
 * Function with 'remaining' in return value
echo secToHR();

And the corresponding outputs :

9 minutes, 20 seconds remaining
3 hours, 2 minutes remaining

I have used this in the Downloader App as I mentioned in the previous post.

Show Comments