Calculate the minute difference between two input time fields

Asked

Viewed 1,937 times

1

How best to calculate the difference of minutes between two camps input time 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 that didn’t work out:

<?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;

?>

Browser inspecting error appears: localhost/php file path: 500 (Internal Server Error).

1 answer

3


Solved.

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 input 07:02 on the first field and 12:20 on the other:

05, 18

So to find only in minutes (as needed), just multiply the first output by 60 and you’re done.

Browser other questions tagged

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