How to Set Value of HTML "time" input Element Using PHP?

The HTML <input type="time"> element expects the value attribute to be set in "hh:mm" (or "hh:mm:ss") 24h-hour format only. Therefore, if you're setting a default value to it using PHP, then you must adhere to the correct date format (i.e. "H:i" or "H:i:s" in PHP).

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

$dt = new DateTime();

echo '<input type="time" value="' . $dt->format('H:i') . '" />';

To include seconds, you can use the "H:i:s" format instead:

$dt = new DateTime();

echo '<input type="time" value="' . $dt->format('H:i:s') . '" />';

To set a specific timezone, you can do the following:

$dt = new DateTime('now', new DateTimeZone('Europe/Berlin'));

echo '<input type="time" value="' . $dt->format('H:i:s') . '" />';

Alternatively, you may set the timezone by calling the DateTime::setTimezone() method on an instance of DateTime:

$dt = new DateTime();
$dt->setTimezone(new DateTimeZone('Europe/Berlin'));

echo '<input type="time" value="' . $dt->format('H:i:s') . '" />';

You can find a list of all supported timezones in PHP in the official documentation.

To set specific time using DateTime (or DateTimeImmutable), you can do the following:

$dt = new DateTime('01 Oct 2022 4:45 pm');

echo '<input type="time" value="' . $dt->format('H:i:s') . '" />';

If you omit the date from the date/time string, then it will consider today's date:

$dt = new DateTime('4:45 pm');

echo '<input type="time" value="' . $dt->format('H:i:s') . '" />';

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('01 Oct 2022 4:45 pm');

echo '<input type="time" value="' . $dt->format('H:i:s') . '" />';

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="time" /> element (depending on the browser and/or the operating system the user is using). For example, a value set to "16:45:00" might be shown to the user as "04:45:00 PM" in the browser. This depends on how the browser/user-agent chooses to display the value.

Before you use the <input type="time"> element, please make sure that you're aware of the browser support.


This post was published 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.