Convert from decimal or integer to php hours

Asked

Viewed 1,469 times

0

I have the result in decimal or integer of hours:

Utilizador 1 = 71.5 horas
Utilizador 2 = 137 horas

I wanted to convert inside php to hours, as an example:

Utilizador 1 = 71:30
Utilizador 2 = 137:00

I’m using this code on while to arrive at hours in decimal or integer:

$Total = 0;
while ($rows_cursos = mysqli_fetch_array($resultado_cursos)) {
  $teste = $rows_cursos['Horas Consumidas'];
  $tempo = explode(":", $teste);
  $tempototal = $tempo[0]*60 + $tempo[1];
  $Total = $Total + $tempototal; 
}
$Total = $Total/60; 

2 answers

1


Simply:

function convertHoras($horasInteiras) {

    // Define o formato de saida
    $formato = '%02d:%02d';
    // Converte para minutos
    $minutos = $horasInteiras * 60;

    // Converte para o formato hora
    $horas = floor($minutos / 60);
    $minutos = ($minutos % 60);

    // Retorna o valor
    return sprintf($formato, $horas, $minutos);
}

In your code:

$Utilizador1 = 0.5;
$Utilizador2 = 137;

echo 'Utilizador 1: ' . $Utilizador1 = convertHoras($Utilizador1) . ' horas';
echo PHP_EOL;
echo 'Utilizador 2: ' . $Utilizador2 = convertHoras($Utilizador2) . ' horas';

Upshot:

Utilizador 1: 00:30 horas
Utilizador 2: 137:00 horas

See working on Ideone

  • 1

    If $minutos is less than 60, $horas will always be 0, then that operation, floor($minutos / 60), would be unnecessary.

  • @Andersoncarloswoss truth man !

  • But how do I apply with the code I have this function?

  • @Beginner I just posted

  • Could even make a if for the calculation of hours if the minutes are less than 60, but I do not see need, because if will arrive condition and execution (in the larger case) would be 2 steps against 1, and if minutes are less, it will be a check step or already the floorstraightforward.

  • I put it like this, but it doesn’t work: $tabela4 .= '<strong>Total de Horas Consumidas:</strong> ' . $Horas = convertHoras($Horas) . ' horas';

  • You are declaring the variable $Horas this way. The correct is ' . echo convertHoras($Horas) . '

Show 2 more comments

0

Browser other questions tagged

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