Does not return date in input

Asked

Viewed 57 times

0

I always want to show the previous Tuesday in the input and for that I do it this way:

$dia = new DateTime();
$dia->modify( 'previous tuesday' );
$terca = date($dia->format('d-m-Y'));

Then I want to show the variable $terca in the value of a input type date, but it doesn’t show, only if it is datetime:

<td style="float:center"> <input type="date" name= "data"  value="<?php echo $terca?>"></td>

Whenever I run the page I get this warning:

The specified value "19-02-2019" does not conform to the required format, "yyyy-MM-dd".

  • You saw what the "required format" is in the error message?

  • @Anderson Carlos Woss The "required format" is the datetime but I want the input to be like date in case you want to change the date the calendar appears. I have tried to convert the variable to date but I still can’t see the date unless I use the datetime

  • 4

    Do not confuse type with format. You tried to insert a value in the d-m-Y format into a field that requires the yyyy-MM-dd format. That’s exactly what the error message says.

  • @Anderson Carlos Woss I’m trying this way date('yyyy-MM-dd', strtotime($terca)); but I still have the same problem

1 answer

3


Do you understand exactly what you are doing or are you trying to code separately? With $dia->format you format your object DateTime for string; then with the function strtotime you create again a date object from your string and then format again for a new string. Even if you are a beginner, avoid making these random attempts. Didn’t it work? Stop and review line by line what you did and see if it makes any sense. In this case did not.

The field <input type="date"> expects a value in yyyyyy-MM-dd format, that is, 4-digit year, 2-digit month (zero left) and 2-digit day (zero left). To generate this with PHP just do:

$dia->format('Y-m-d');

For more details of what each letter does read the documentation.

For example:

$dia = new DateTime();
$dia->modify( 'previous tuesday' );
$terca = $dia->format('Y-m-d');

echo sprintf('<input type="date" value="%s">', $terca);

What generates:

<input type="date" value="2019-02-19"> 

Browser other questions tagged

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