Categories
JavaScript Answers

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

Spread the love

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).

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *