How to set a value for the input type 'datetime-local'?

Jbadminton picture Jbadminton · Nov 28, 2016 · Viewed 51.9k times · Source

I tried this:

<input type="datetime-local"  value="<?php echo $row['Time']; ?>" class="date" name="start" REQUIRED>

How can I set the value of this input field with the data from the database?
It doesn't work!!
I need to make it possible to edit too.
Or should I use another type of input?
$row['Time'] is from the database!

Answer

Karol Gasienica picture Karol Gasienica · Nov 28, 2016

I don't know exacly what is in $row['Time'] but it should be as follows:

Definition

A valid date-time as defined in RFC 3339 with these additional qualifications:

  • the literal letters T and Z in the date/time syntax must always be uppercase
  • the date-fullyear production is instead defined as four or more digits representing a number greater than 0

Examples

  • 1990-12-31T23:59:60Z
  • 1996-12-19T16:39:57-08:00

Solution

To create RFC 3339 format in PHP you can use:

echo date('Y-m-d\TH:i:sP', $row['Time']);

or in another way:

echo date("c", strtotime($row['Time']));  

or if you prefer objective style:

echo (new DateTime($row['Time']))->format('c');

In your code

So in your code it would look as follows:

<input type="datetime-local"  value="<?php echo date('Y-m-d\TH:i:sP', $row['Time']); ?>" class="date" name="start" REQUIRED>

or

<input type="datetime-local"  value="<?php echo date("c", strtotime($row['Time'])); ?>" class="date" name="start" REQUIRED>

Manual