How to check time entry and cancel calculation when come blank

Asked

Viewed 39 times

3

I’m calculating the difference between two times using , 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 :

$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 issetand 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?

1 answer

2


I believe you have to check before you do anything. Like:

//se for diferente de null, faz o calculo
if ($val1 <> null and $val2 <> null) {

$datetime1 = new DateTime("2017-04-05, $val1");
$datetime2 = new DateTime("2017-05-06, $val2");
$horario1 = $intervalo->h; // DIFERENÇA EM HORAS (INT)
$horario2 = $intervalo->i; // PEGA OS MINUTOS 
}

if one of the two is equal to NULL it does nothing.

  • It sounds like a really good idea, I’m gonna try it out... +1

Browser other questions tagged

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