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

Adding a default value to HTML input element with type set to "month" using PHP

The HTML <input type="month"> element expects the value attribute to be set in "YYYY-MM" 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-m" in PHP).

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

$dt = new DateTime();

echo '<input type="month" value="' . $dt->format('Y-m') . '" />';

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

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

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

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('Oct 2022');

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

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

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


Hope you found this post useful. It was published . Please show your love and support by sharing this post.