Problems displaying duration in hours and minutes in PHP

0

I am trying to calculate a duration between values of a column in my database. The value until it is being calculated correctly, but it turns out that the hour: minute format is not going as expected.

Assuming that in my database I have the first duration that is 1:30 and the second duration is 2:30, it will total 4:00 p.m., but what comes out to me on screen is 4: 0 How can I resolve this?

Here is part of my code that does the operation:

$query = mysql_query("SELECT ass.Duracao, pa.horas_dadas, pa.Horas_restantes, pa.Qtd_horas, ass.ID_Aluno, ass.ID_Pacote, ass.ID_Aula, pa.id_alunos FROM Assiste ass JOIN pacotes pa ON pa.ID=ass.ID_Pacote WHERE ID_Aluno = $pegaid AND ID_Pacote = $pegaid_pacote AND Status_presence = 'Ativa'"); 

while($row = mysql_fetch_array($query)) 
{ 
    $hora= $row['Duracao']; 
    $show_qtd_horas = $row['Qtd_horas']; 
    $hora1 = explode(":",$hora); 
    $min_hora1 = ($hora1[0] * 3600) + ($hora1[1] * 60); 
    $total=$total+$min_hora1; 
} 

$hora = floor($total / 3600); 
$total = $total - ($hora * 3600); 
$min = floor($total / 60)/10; 
$min=str_replace(".","",$min);
$result_duracao=$hora.":".$min; 

if(strlen($min)==1)
{ 
    $min=$min."0"; 
} 

$update_pacotes = mysql_query("UPDATE pacotes SET horas_dadas='$result_duracao' WHERE id_alunos=$pegaid AND ID=$pegaid_pacote");

echo $result_duracao;
    
asked by anonymous 10.05.2017 / 22:38

2 answers

1
   while($row = mysql_fetch_array($query)) 
   { 
     $hora= $row['Duracao']; 
     $show_qtd_horas = $row['Qtd_horas']; 
     $hora1 = explode(":",$hora); 

     $min_hora1 = ($hora1[0] * 3600) + ($hora1[1] * 60); 
     $total=$total+$min_hora1; 
   } 
     $hora = floor($total / 3600); 
     $total = $total - ($hora * 3600); 
     $min = floor($total / 60)/10; 
     $min=str_replace(".","",$min);
     $result_duracao=$hora.":".$min; 
     if(strlen($min)==1){ 
        $result_duracao=$result_duracao."0"; 
     } 

      $testeHora = explode(":",$result_duracao);
      $lenHora= strlen($testeHora[0]);

      if($lenHora==1){ 
        $result_duracao="0".$result_duracao; 
      }
  

1: In your code change $min=$min."0"; to $result_duracao=$result_duracao."0";

     

2: Add these lines to the end of the code before the update.

 $testeHora = explode(":",$result_duracao);
 $lenHora= strlen($testeHora[0]);
    if($lenHora==1){ 
      $result_duracao="0".$result_duracao; 
    }
  

which will check if the part of the time contains 1 or 2 digits. If it has a digit it will concatenate with a 0 in front.

    
11.05.2017 / 04:10
0

If the calculation is correct you can use a php native date function to display in the correct pattern.

echo date('H:i', strtotime($nomedavariavel));

See the example using your phpFiddle code

    
10.05.2017 / 22:55