Home > Net >  How to make $date show on input type="date"
How to make $date show on input type="date"

Time:01-04

All the "date" in my database are of the following format: 'd-m-Y' (E.g. 09-03-2022)

I want have a field with input type=date, so user can modify the date.

I use the following code to pull data:

$date      = "<input type=\"date\" id=\"date\" size= \"50%;\" name=\"date\" value=\"$res[date]\" >";

...
<thead> <th>Date </th> <td>$date </td> </thead>

But my inputbox is showing dd/mm/yyyy instead of the actual date.

enter image description here

What formatting do I need to do to make my actual date show on the inputbox?

I have tried the following but doesn't work:

$date      = "<input type=\"date\" id=\"date\" size= \"50%;\" name=\"date\" value=\"date('d-m-Y',$res[date])\" >";

CodePudding user response:

You are passing a wrong format to your date input. Date input must fill with RFC3339 formatted text, you can read more about it.

To change your current format to Y-m-d format, you can use below code:

DateTime::createFromFormat('d-m-Y', $dateInput)->format('Y-m-d');

If you are using MySQL, it uses YYYY-MM-DD format for date type column, so, saving the date with Y-m-d from PHP to MySQL date field seems to be the correct way.

CodePudding user response:

So I believe the reason why the date is not displaying on my input field is becuz it is in String datatype and need to format to DATE.

$date1  =   date_create("$res[date]");
$date2  =   date_format($date1,"Y-m-d");
$date   = "<input type=\"date\" id=\"date\" size= \"50%;\" name=\"date\" value=\"$date2\" >";

With this, I can also do the same for TIME

$time1  =   date_create("$res[time]");
$time2  =   date_format($time,"H:i:s");
$time   = "<input type=\"time\" id=\"time\" size= \"50%;\" name=\"time\" value=\"$time2\" >";
  • Related