Ask Your Question
1

What is the process for using a JavaScript Date object to assign a value to an html input with the type datetime-local?

asked 2021-05-21 11:00:00 +0000

scrum gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
1

answered 2023-01-02 19:00:00 +0000

david gravatar image

Here is the process to use a JavaScript Date object to assign a value to an HTML input with the type datetime-local:

  1. Create a new Date object and set the desired date/time values.
var date = new Date();
date.setFullYear(2022);
date.setMonth(0);
date.setDate(31);
date.setHours(12);
date.setMinutes(0);
date.setSeconds(0);
  1. Get a reference to the desired HTML input element.
var input = document.getElementById('datetime-input');
  1. Format the date/time string in ISO format, which is required by the datetime-local input type.
var dateTimeString = date.toISOString().substring(0, 16);
  1. Set the value of the HTML input element to the formatted date/time string.
input.value = dateTimeString;

This will set the value of the input to "2022-01-31T12:00".

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2021-05-21 11:00:00 +0000

Seen: 13 times

Last updated: Jan 02 '23