How to set the value of a datetime-local input to a date with JavaScript?

Sometimes, we want to set the value of a datetime-local input to a date with JavaScript.

In this article, we’ll look at how to set the value of a datetime-local input to a date with JavaScript.

How to set the value of a datetime-local input to a date with JavaScript?

To set the value of a datetime-local input to a date with JavaScript, we can set the input value to a date string.

For instance, we write:

<input id="dt" type="datetime-local" />

to add the datetime-local input.

Then we write:

const now = new Date();
now.setMinutes(now.getMinutes() - now.getTimezoneOffset());
document.getElementById('dt').value = now.toISOString().slice(0, 16);

We create the now date with the Date constructor.

Then we call setMinutes to change the time to local time by calling it with now.getMinutes() - now.getTimezoneOffset().

Next we set the value of the input with:

document.getElementById('dt').value = now.toISOString().slice(0, 16);

We set the value to a date string by taking the first 16 characters of the date time string with now.toISOString().slice(0, 16).

Conclusion

To set the value of a datetime-local input to a date with JavaScript, we can set the input value to a date string.