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

The HTML <input type="week"> element expects the value attribute to be set in "YYYY-Www" (ISO8601 week number) format. Therefore, if you're setting a default value to it using PHP, then you must adhere to the correct date format (i.e. "Y-\WW" in PHP).

For example, you can set the current year-week pair using DateTime (or DateTimeImmutable), in the following way:

$dt = new DateTime();

echo '<input type="week" value="' . $dt->format('Y-\WW') . '" />';

Similarly, you can set a specific year-week pair using DateTime (or DateTimeImmutable), in the following way:

$dt = new DateTime('01 Oct 2022');

echo '<input type="week" value="' . $dt->format('Y-\WW') . '" />';

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');

echo '<input type="week" value="' . $dt->format('Y-\WW') . '" />';

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="week" /> element (depending on the browser and/or the operating system the user is using). For example, a value set to "2022-W39" might be shown to the user as "Week 39, 2022" in the browser. This depends on how the browser/user-agent chooses to display the value.

Before you use the <input type="week"> 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.