set date to input date js

How to Set Date to Input Date in JavaScript

If you want to set the date to input date using JavaScript, you can use the Date object. The Date object represents a specific moment in time and allows you to work with dates and times.

Method 1:

Here is a simple example code to set the date value to an input date element:


const inputDate = document.querySelector('#input-date');
const date = new Date();
inputDate.value = date.toISOString().substr(0, 10);
    

The above code gets the input date element using querySelector and sets its value to the current date using the Date object. The toISOString() method is used to convert the date to ISO format, and the substr() method is used to extract the first 10 characters, which represent the date part.

Method 2:

You can also set a specific date value to an input date element using the Date object. Here is an example:


const inputDate = document.querySelector('#input-date');
const date = new Date('2021-09-01');
inputDate.value = date.toISOString().substr(0, 10);
    

The above code sets the input date value to September 1, 2021, by creating a new Date object with the specified date string.

Method 3:

You can also set a date value to an input date element using the setDate(), setMonth(), and setFullYear() methods of the Date object. Here is an example:


const inputDate = document.querySelector('#input-date');
const date = new Date();
date.setDate(1);
date.setMonth(8);
date.setFullYear(2021);
inputDate.value = date.toISOString().substr(0, 10);
    

The above code sets the input date value to September 1, 2021, by creating a new Date object with the current date and then setting the day, month, and year using the setDate(), setMonth(), and setFullYear() methods.

These are some simple ways to set the date to input date in JavaScript.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe