How to transform a value into seconds? For example: 01:32, in case it would be 92 seconds.
I would like to do this in php, I already searched the net but found nothing.
How to transform a value into seconds? For example: 01:32, in case it would be 92 seconds.
I would like to do this in php, I already searched the net but found nothing.
One option would be to use explode
:
$tempo = "01:32";
$segundos = explode(":",$tempo);
$total = ((int)$segundos[0] * 60) + (int)$segundos[1];
echo $total;
Another option would be to use strtotime
$tempo = "00:01:32";
$total = strtotime('1970-01-01 '.$tempo .'UTC');
echo $total;
As elucidated by @bfavaretto, this option has a limit of 89999 seconds for it to function properly. That is, the threshold value to convert from 24 hours, 59 minutes and 59 seconds .
If you have the time parameter in the first option, you can use it like this:
$tempo = "01:01:32";
$segundos = explode(":",$tempo);
$total = ((int)$segundos[0] * 60 * 60)+ ((int)$segundos[1] * 60) + (int)$segundos[2];
echo $total;
$tempo_total= "4:44";
sscanf($tempo_total, "%d:%d:%d", $horas, $minutos, $segundos);
$tempo_segundos = isset($segundos) ? $horas * 3600 + $minutos * 60 + $segundos : $horas * 60 + $minutos;
It is not the best solution (the best is Daniel Gomes Da Silva), but also serves to represent a duration with 25+ hours in addition to putting some knowledge in practice in PHP
$tempo_total= "30:4:44";
if (substr_count($tempo_total, ':')==2){
$tempo_segundos = (int)$tempo_total*3600 + (int)(substr(strstr($tempo_total, ':'), 1))*60 + substr($tempo_total, -2);
}else{
$tempo_segundos = (int)$tempo_total*60 + substr($tempo_total, -2);
}
echo $tempo_segundos; //108284
1 - The conversion of string to integer depends on the format of the string, so PHP evaluates the format of the string and if it does not have any numerical value will be converted to 0 (zero). If you have numeric value in its first position the value will be considered and if the value is not in the first position it will be disregarded. example in ideone
$tempo_total= "30:4:44";
$num = (int)$tempo_total;
var_dump ($num); // int(30)
2 - substr_count($tempo_total, ':')
counts the number of occurrences of the character :
(colon) to apply to the conditional, if equal to 2 means that the variable $tempo_total
is formed by hours, minutes and seconds and executes if
and otherwise executes else
3 - strstr($tempo_total, ':')
- returns part of the string $tempo_total
from the first occurrence of :
to the end, in this case it returns :4:44
4 - substr(strstr($tempo_total, ':'), 1)
- returns part of the return of the item above :4:44
from position 1, ie 4:44
. Converting to integer (see item 1) we have: example in ideone
$num = (int)"4:44";
var_dump ($num); // int(4)
5 - substr($tempo_total, -2)
- a negative index, this way PHP parses the string counting N characters from the end