Sum of hours greater than 24 hours

Asked

Viewed 223 times

6

I have a variable with the value '18:00', which corresponds to a duration received through calculations between two times.

$tempo = '18:00'; // queria somar 8:00

Answer:

$temposomado = '2:00';

Intended value:

$temposomado = '26:00'

How can I get this second result in PHP?

  • Probably it is considering as hours, I believe that to sum the minutes you should do: $time = '00:18'; For it to consider the minutes

  • this is as string yet.

  • It’s time... imagine 18:00:00. It can also be...

  • PHP has the Datetime object to work with time. You’ve already seen something about?

  • yes I got to see @gmsantos, but for now, this was the best chance for the case I’m developing.

  • Friend, I think you should consider one of the correct answers. I believe that either "I like Trains" or Isac. In my opinion they are the best. Hug!

  • 1

    I’ve put the right answer :)

Show 2 more comments

5 answers

5

Well, first you can take only the hours and minutes, then add up

$tempo="18:40";
$tempo2="08:30";

$minutos1=substr($tempo, 3, 2);
$minutos2=substr($tempo2, 3, 2);
$soma_min=(int)$minutos2+(int)$minutos1;
if($soma_min > 60){
   $hora_mais=1;
   $soma_min=$soma_min-60;
}else{
   $hora_mais=0;
}
if($soma_min<10){
    $soma_min=$soma_min."0";
}
$hora1 = substr($tempo, 0, 2);
$hora2 = substr($tempo2, 0, 2);

$hora_somada= (int)$hora2+(int)$hora1+$hora_mais;
$tudo_junto=$hora_somada.":".$soma_min;
echo $tudo_junto;

5


Although the other answers are right, they are not adding up the seconds. So I decided to create an alternative.

I made that response based on in this answer and in this answer

$tempo_inicial= "18:59:59";
 $tempo_somado= "07:00:01";

 sscanf($tempo_inicial, "%d:%d:%d", $horas_inicial, $minutos_inicial, $segundos_inicial);
 sscanf($tempo_somado, "%d:%d:%d", $horas_somado, $minutos_somado, $segundos_somado);

 $tempo_segundos_inicial = $horas_inicial * 3600 + $minutos_inicial * 60 + (isset($segundos_inicial) ? $segundos_inicial : 0);
 $tempo_segundos_somado = $horas_somado * 3600 + $minutos_somado * 60 + (isset($segundos_somado) ? $segundos_somado : 0);
 $total = $tempo_segundos_inicial + $tempo_segundos_somado;

 $horas = floor($total / 3600);
 $minutos = floor(($total - ($horas * 3600)) / 60);
 $segundos = floor($total % 60);

 $temposomado = sprintf('%02d:%02d:%02d', $horas, $minutos, $segundos);

 echo $temposomado; // saída será 26:00:00

See working on ideone

So, a version of my role AddPlayTime @Wictorchaves response based on the example above would be like this:

$times = array();

$times[] = "18:59:59";
$times[] = "07:00";
$times[] = "00:00:01";

echo AddPlayTime2($times);

function AddPlayTime2($times) {
    $total = 0;
    foreach ($times as $time) {
        if(substr_count($time, ":") == 1)
            $time .= ":00";
        sscanf($time, "%02d:%02d:%02d", $hour, $minute, $second);
        $total += $hour * 3600 + $minute * 60 + $second;
    }

    $horas = floor($total / 3600);
    $minutos = floor(($total - ($horas * 3600)) / 60);
    $segundos = floor($total % 60);

    return sprintf('%02d:%02d:%02d', $horas, $minutos, $segundos);
}

4

You can do this with this function:

AddPlayTime($times);

An example:

$times = array();

$times[] = "18:00";
$times[] = "8:00";

echo AddPlayTime($times);

function AddPlayTime($times) {
    $minutes = 0; 
    foreach ($times as $time) {
        list($hour, $minute) = explode(':', $time);
        $minutes += $hour * 60;
        $minutes += $minute;
    }

    $hours = floor($minutes / 60);
    $minutes -= $hours * 60;

    //Aqui ele verifica se passou de 24 hs
    if($hours > 24){
        $vezes = $hours / 24;
        $hours = $hours - (24*intval($vezes));
    }
    return sprintf('%02d:%02d', $hours, $minutes);
}

You create an array of times you want to add and send to function.

UPDATE

I interpreted the question differently, but according to Andrei Coelho he needs the sum of the terms, so just remove the if, as in this example:

$times = array();

$times[] = "18:00";
$times[] = "8:00";

echo AddPlayTime($times);

function AddPlayTime($times) {
    $minutes = 0; 
    foreach ($times as $time) {
        list($hour, $minute) = explode(':', $time);
        $minutes += $hour * 60;
        $minutes += $minute;
    }

    $hours = floor($minutes / 60);
    $minutes -= $hours * 60;

    return sprintf('%02d:%02d', $hours, $minutes);
}

Based on: https://stackoverflow.com/questions/22681725/how-to-sum-n-number-of-time-hhmm-format

  • 2

    Although I have given +1 to your publication is not responding. Your publication returns 2h. He wants just the sum of time. In case 26h

  • 2

    I made a change, so it fits both ways

4

A form that I find simple:

// Variáveis recebidas
$hora1 = '09:15';
$hora2 = '19:30';

// Quebra horas de minutos
$t1 = explode(':', $hora1);
$t2 = explode(':', $hora2);

// Converte para minutos e soma
$min_1 = ($t1[0] * 60 + $t1[1]);
$min_2 = ($t2[0] * 60 + $t2[1]);
$min_t = $min_1 + $min_2;

// Define o formato
$formato = '%02d:%02d';

// Converte os minutos para horas e minutos
$horas = floor($min_t / 60);
$minutos = ($min_t % 60);

// Imprime
echo 'Hora: ' . sprintf($formato, $horas, $minutos);

Here I use the same script to print ranges:

Problems when generating schedules dynamically

  • I thank you, but this reply still gives me hours of no more than 24.

  • Strange, because I tested it here, I tested it now on http://phptester.net/, and it’s normal. You need to see how it’s printing, if you’re not changing some property.

4

You already have several options to choose from, but I choose to make my contribution with a slightly different one, although similar to @Andreicoelho. Like his, my implementation also takes seconds into account.

Implementation:

function obterSegundos($tempo){
    $tempos = explode(":", $tempo);
    $horasmins = (int)$tempos[0] * 3600 + (int)$tempos[1] * 60;
    return count($tempos) === 2 ? $horasmins : $horasmins + (int)$tempos[2];
}

function formatarSegundos($total){
    $horas = floor($total / 3600);
    $minutos = floor(($total - $horas * 3600) / 60);
    $segundos = $total % 60;
    return $segundos ? 
        sprintf('%02d:%02d:%02d', $horas, $minutos, $segundos):
        sprintf('%02d:%02d', $horas, $minutos);
}

$t1 = "18:00";
$t2 = "08:30:09";
$total = obterSegundos($t1) + obterSegundos($t2);
$t3 = formatarSegundos($total); //26:30:09

Watch it work on Ideone

Testing:

$t1 = "11:05";
$t2 = "05:35";
$t3 = formatarSegundos(obterSegundos($t1) + obterSegundos($t2)); //16:40

$t1 = "18:00:59";
$t2 = "08:00:55";
$t3 = formatarSegundos(obterSegundos($t1) + obterSegundos($t2)); //26:01:54

$t1 = "12:00:05";
$t2 = "01:30";
$t3 = formatarSegundos(obterSegundos($t1) + obterSegundos($t2)); //13:30:05

$t1 = "11:55";
$t2 = "01:56";
$t3 = formatarSegundos(obterSegundos($t1) + obterSegundos($t2)); //13:51

$t1 = "1:05";
$t2 = "2:10";
$t3 = formatarSegundos(obterSegundos($t1) + obterSegundos($t2)); //03:15
  • Very good your function obterSegundos()

  • 1

    If he chooses only by performance, he will choose "I Like Trains", but if he chooses performance and the seconds parameter he would have to choose his. See: https://ideone.com/PyMIV5

  • 1

    @Interesting Andreicoelho this ideone that you rode :). At the end of the day mine is very similar to yours, I would even say almost a variant.

  • I’m not so interested in seconds because we only deal with hours and minutes.

  • 1

    @White It works in both cases, so there is no risk of breaking, if later on you want to interpret also the seconds. And it also doesn’t force you to have two digits in each part.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.