|
From Seconds until Hours, Minutes and Seconds |
|
|
|
As to go from seconds until Hours (if they are), Minutes (if they are) and Seconds. For example if I have 28240 Seconds, like doing that it prints: 7:50:40 AM Hours
The process is undoubtedly simple, let's see the code and then the explanation:
Code Source:
<?
function segundos_tiempo ($segundos) {
$minutos=$segundos/60;
$horas=floor ($minutos/60);
$minutos2=$minutos%60;
$segundos_2=$segundos%60%60%60;
if ($minutos2 <10) $minutos2 = '0 '.$minutos2;
if ($segundos_2 <10) $segundos_2 = '0 '.$segundos_2;
if ($segundos <60) {/* seconds */
$resultado = round ($segundos).' Seconds';
} elseif ($segundos> 60 && $segundos <3600) {/* minutes */
$resultado = $minutos2.': '.$segundos_2.' Minutes';
} else {/* hours */
$resultado = $horas.': '.$minutos2.': '.$segundos_2.' Hours';
}
return $resultado;
}
$segundos=date ('h') *60*60 + (I dated ('i') *60) +date ('s');
I begin 'Seconds: '.$segundos.' Result: '.segundos_tiempo ($segundos);
?>
Explaining:
We define a function with the name of segundos_tiempo (ARG1), where the ARG1 is the value that we indicate (seconds) when we call the function.
We will realize a series of arithmetical operations, then to determine the result.
$Minutos, as one sees; it will be equal to the division between $segundo and 60.
Example: 120 seconds / 60 is equal to 2 minutes.
$horas it is equal to the division of $minutos between 60, and we it round down with the mathematical function floor ()
$minutos2 it will be equal to the residue (the rest) returned by the division between $minutos and 60.
And $segundos_2 the residue of the division between $segundos, 60, 60, 60 successively.
That are only the information accumulated in the previous processes.
Then we initiate a condition to verify if the number is minor to 10 and to place 0 (zero) to the beginning: For example 9 => 09, we repeat the process with the seconds and minutes, with the hours it would be unnecessary.
We create another condition to indicate if it has been defined Hours, minutes ó the second and to return the format and correct style.
If $segundos it is minor than 60 (then only there are seconds)
if ($segundos <60)
Otherwise if $segundos it is minor than 60 and is minor than 3600 (minutes have been defined and seconds)
elseif ($segundos> 60 && $segundos <3600)
Otherwise to all these (it has been defined hours, minutes and seconds)
else
Finally we return the result
return $resultado;
And we apply the function, with the second current ones of the servant to verify that he returns us the exact hour.
Emmanuel García De Caro
http://www.blasten.com/contenidos/19077 |