Calculate the time difference between two input time fields

1

What is the best way to calculate the difference of minutes between two input time fields with PHP?

Example of two fields input :

<label for="Cseg3">Horário 1:</label>
<input type="time" id="Cseg3" name="Tsegs">
<label for="Cseg4">Horário 2:</label>
<input type="time" id="Cseg4" name="Tsegss">

An attempt with Datetime :: dif did not work:

<?php
setlocale(LC_ALL, 'pt_BR', 'pt_BR.utf-8', 'pt_BR.utf-8', 'portuguese');
date_default_timezone_set('America/Sao_Paulo');

$val1 = $_POST ["Tsegs"];
$val2 = $_POST ["Tsegss"];

$datetime1 = new DateTime($val1);
$datetime2 = new DateTime($val2);


$intervalo = $datetime1->diff($datetime2);
echo $intervalo;

?>

Inserting the browser appears the error: localhost / file path php: 500 (Internal Server Error).

    
asked by anonymous 17.04.2015 / 01:01

1 answer

3

Resolved.

The problem was in print format. The correct one, for time fields, is:

echo $intervalo->format('%H, %i');

So it will return difference in hours and minutes. This is the code that worked for me:

<?php

$val1 = $_POST ["Tsegs"];
$val2 = $_POST ["Tsegss"];

$datetime1 = new DateTime($val1);
$datetime2 = new DateTime($val2);

$intervalo = $datetime1->diff($datetime2);

echo $intervalo->format('%H, %i');

?>

This is an output for the 7:02 input on the first field and 12:20 on the other:

  

05, 18

So, to find only in minutes (as needed), just multiply the first exit by 60 and that's it.

    
17.04.2015 / 03:00