How to Set Value of HTML "datetime-local" input Element Using PHP?

The HTML <input type="datetime-local"> element expects the value attribute to be set in "YYYY-MM-DDThh:mm" format (as defined by RFC 3339). Therefore, if you're setting a default value on it using PHP, then you must adhere to the correct date format (i.e. "Y-m-d\TH:i" in PHP).

For example, you can set the current date-time using DateTime (or DateTimeImmutable), in the following way:

$dt = new DateTime();

echo '<input type="datetime-local" value="' . $dt->format('Y-m-d\TH:i') . '" />';

Similarly, you can set a specific date-time using DateTime (or DateTimeImmutable), in the following way:

$dt = new DateTime('2022-10-16 04:45:00');

echo '<input type="datetime-local" value="' . $dt->format('Y-m-d\TH:i') . '" />';

There are several other ways in which you can create a formatted date in PHP. For example, you may use the date_create() function as an alternative, which creates a new DateTime object:

$dt = date_create('16 Oct 2022 4:45 am');

echo '<input type="date" value="' . $dt->format('Y-m-d\TH:i') . '" />';

Please note that the value that's actually displayed in the browser might be in a different format than the one you use on the value property of <input type="datetime-local" /> element (depending on the browser and/or the operating system the user is using). For example, a value set to "2022-10-16T04:45" might be shown to the user as "16.10.2022, 04:45 AM" in the browser. This depends on how the browser/user-agent chooses to display the value.


This post was published (and was last revised ) by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.