Categories
JavaScript Answers

How to set datetime on a datetime-local input with JavaScript?

Spread the love

Sometimes, we want to set datetime on a datetime-local input with JavaScript.

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

How to set datetime on a datetime-local input with JavaScript?

To set datetime on a datetime-local input with JavaScript, we can convert the datetime to a local datetime string.

For instance, we write:

<input type="datetime-local" id="publishDate" required/>

to add a datetime-local input.

Then we write:

const now = new Date();
const input = document.querySelector('input')
input.value = new Date(now.getTime() - now.getTimezoneOffset() * 60000).toISOString().substring(0, 19);

We select the input with document.querySelector.

Then we write new Date(now.getTime() - now.getTimezoneOffset() * 60000) to convert the current datetime to local datetime.

Then we call toISOString to convert it into a datetime string.

And finally, we call substring to extract the datetime part from the string.

Then we set that as the value of the input.

Conclusion

To set datetime on a datetime-local input with JavaScript, we can convert the datetime to a local datetime string.

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 *