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

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 its value using JavaScript, you must adhere to the correct format.

The Date.prototype.toISOString() method returns date/time in UTC (with the suffix "Z" denoting that timezone). Therefore, if you remove the "Z", it would provide a value in the format expected by the datetime-local input. You can do this, for example, in the following way:

const dt = new Date();
dt.setMinutes(dt.getMinutes() - dt.getTimezoneOffset());
console.log(dt.toISOString().slice(0, 16)); // '2022-10-16T04:45'

To demonstrate this with a complete, working example, consider the following <input> field:

<input id="booking" type="datetime-local" name="date_booking" />

To set its value using JavaScript, you would do the following:

function datetimeLocal(datetime) {
    const dt = new Date(datetime);
    dt.setMinutes(dt.getMinutes() - dt.getTimezoneOffset());
    return dt.toISOString().slice(0, 16);
}

const booking = document.getElementById('booking');
booking.value = datetimeLocal('2022-10-16 04:45:00');

This would set the value of the <input type="datetime-local"> element to "2022-10-16 04:45:00" (i.e. 16 October 2022 4:45 am).

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-16 04:45:00" 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 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.