Register now and start sharing your code snippets.
-->

How to format number of seconds as duration with PHP

PHP posted 11 months ago by christian

A very sophisticated algorithm that will display the length of, for example, a video as 12:01:30.

   1  function duration($seconds_count)
   2  	{
   3  		$delimiter  = ':';
   4  		$seconds = $seconds_count % 60;
   5  		$minutes = floor($seconds_count/60);
   6  		$hours   = floor($seconds_count/3600);
   7  
   8  		$seconds = str_pad($seconds, 2, "0", STR_PAD_LEFT);
   9  		$minutes = str_pad($minutes, 2, "0", STR_PAD_LEFT).$delimiter;
  10  
  11  		if($hours > 0)
  12  		{
  13  			$hours = str_pad($hours, 2, "0", STR_PAD_LEFT).$delimiter;
  14  		}
  15  		else
  16  		{
  17  			$hours = '';
  18  		}
  19  
  20  		return "$hours$minutes$seconds";
  21  	}

Tagged php, duration, format, time, seconds