3
I’m calculating the difference between two times using datetime, but when a time is not filled I need him to do no calculation (the result needs to be 0
or NULL
), but he calculates considering 00:00.
So if for example the final field was filled with 7:00 pm, and the other one was not filled in, he should not calculate anything, but still he accuses a difference of 7 hours. Or if it’s the other way around, it counts 17 hours...
The form:
<label class="form-inline" for="Cseg3">Horário 1:
<input type="text" id="Cseg3" name="Tsegs" class="form-control horario tempo linha1"></label>
<label class="form-inline" for="Cseg4">Horário 2:
<input type="text" id="Cseg4" name="Tsegss" class="form-control horario tempo linha1"></label>
Take the form data:
$val1 = isset($_POST["Tsegs"]) ? $_POST["Tsegs"] : NULL;
$val2 = isset($_POST["Tsegss"]) ? $_POST["Tsegss"] : NULL;
Converts to dateinterval:
$datetime1 = new DateTime("2017-04-05, $val1");
$datetime2 = new DateTime("2017-05-06, $val2");
Finding the difference:
$intervalo = $datetime1->diff($datetime2);
Turns objects into variables:
$horario1 = $intervalo->h; // DIFERENÇA EM HORAS (INT)
$horario2 = $intervalo->i; // PEGA OS MINUTOS
I already tried to get the form data with some variations of isset
and empty
, guy:
$val1 = isset($_POST["Tsegs"]) ? $_POST["Tsegs"] : NULL;
$val1 = empty($_POST["Tsegs"]) ? NULL : $_POST["Tsegs"];
But he always considers 00:00. A var_dump
of $val1
returns (when not filled in):
string(0) ""
So the question is: How do I so that when a field is not filled in, it does not perform the calculation?
It sounds like a really good idea, I’m gonna try it out... +1
– gustavox