Hours manipulation [HH:MM:SS] - php and mysql

Asked

Viewed 259 times

0

Good afternoon, you guys.

I need to manipulate time fields [HH:MM:SS] in PHP itself.

I take the text values in the HTML form as in the following example:

 <div class="item form-group">
                        <label class="control-label col-md-3 col-sm-3 col-xs-12">P.E: <span data-toggle="tooltip" title=Horário de entrada" class="required">*</span></label>
                        <div class="col-md-9 col-sm-9 col-xs-12">
                          <input type="text" name="hora_entrada" class="form-control" data-inputmask="'mask' : '99:99:99'" placeholder="HH:MM:SS" required="">
                        </div>
                      </div>

  <div class="item form-group">
                        <label class="control-label col-md-3 col-sm-3 col-xs-12">S.B.: <span data-toggle="tooltip" title="Horário de saída class="required">*</span></label>
                        <div class="col-md-9 col-sm-9 col-xs-12">
                          <input type="text" name="hora_saida" class="form-control" data-inputmask="'mask' : '99:99:99'" placeholder="HH:MM:SS" required="">
                        </div>
                      </div>

Bring to the PHP script to do the calculation:

$saida = $_POST['saida'];
$entrada = $_POST['entrada'];

//cálculo do hora trabalhada

	 		$ps = strtotime($saida);
	 		$pe = strtotime($entrada);

	 		$horas = ($ps-$pe);

So if I put 14:20:00 - 06:00:00, the result should be 08:20:00

But it’s coming: 00:08:00

Does anyone know how I can make these calculations?

Thank you

  • 1

    With this data you test $horas is worth 30000, that is, the difference in seconds (which equals 8:20). I think it is correct.

  • It is that I would like the formatted value. Moreover, it shows 00:08:00 in the table field which is of the time type

1 answer

2


Your calculation is correct, you just need to hit the display, which can be done as follows:

$ps = "14:20:00";
$pe = "06:00:00";

$ts1 = strtotime( $ps);
$ts2 = strtotime($pe);
$diff = abs($ts1 - $ts2); // diferença entre os dois tempos

echo gmdate("H:i:s", $diff); // transformação do valor numérico $diff em hora string novamente
  • It worked. Thank you! Could you tell me the difference between date and gmdate (I didn’t know this one)?

  • 1

    According to the documentation of the two functions in PHP.net, date() uses as Timezone the regulated on your server, while gmdate() uses greenwitch Timezone.

  • I get it. Thank you.

Browser other questions tagged

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