How to modify unfilled date in the form for the current day?

Asked

Viewed 155 times

1

I tried to do with isset, guy:

$var1 = isset($_POST["namedocampo"]) ? $_POST["namedocampo"] : date('d/m/Y');

And with if, guy:

if ($_POST["namedocampo"] == "") {

$var1 = date('d/m/Y');

}

But whenever the field is not filled in the date appears 31/12/1969.

The date input field looks like this:

<input type="text"  id="iddocampo" name="namedocampo" class="form-control" maxlength="10" placeholder="dd/mm/aaaa" onkeyup="formatar('##/##/####', this, event)"></label>

And the exit field is like this:

<li class="list-group-item">
<span class="badge"><?php echo date("d-m-Y",strtotime($var1)); ?></span>
Data:
</li>
  • 1

    Have you tried looking in the Firefox/Chrome console to see what the form is sending to the server? You would expect this keyup ensure that the empty field sends the empty string to the server, but this is actually what is happening?

  • That one keyup is to call a function in js to format the date and validate the field to open a button. The answer below worked... Thanks.

2 answers

1


First check whether the method of your form is like POST

Below is an example:

<form action="arquivo.php" method="post">
    Data: <input type="text" name="data"/>
</form>

php file.

<?php
    $data = empty($_POST["data"]) ? date("d/m/Y") : $_POST["data"];
    echo $data;

For strtotime to work the date needs to be in one of the patterns described in http://php.net/manual/en/function.strtotime.php

For your exit try the code below

date("d/m/Y",strtotime(str_replace('/', '-', '27/05/1990'))); 
  • It worked just by using the empty, nor did I need to change anything on the way out. Thanks!

1

What happens is this: If strtotime($var1) returns false then date("d-m-Y",strtotime($var1)); sets the default date 31/12/1969.

To resolve this check strtotime($var1).

$time = strtotime($var1);
$date = ($time === false) ? '0000-00-00 00:00:00' : date('Y-m-d H:i:s', $time);
echo $date;

Browser other questions tagged

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