Skip to content
the poor coder

set date to input date js

Poor Man
Published
Reading time
1 min read
On this page

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:

JavaScript

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:

JavaScript

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:

JavaScript

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.

Keep going

2023

how to sort an array

How to Sort an Array If you have an array and you want to order its elements in a specific way, you need to use a sorting algorithm. There are several sorting algorithms available, but two of the most commonly used are…

javascript2 min read
2023

jquery mobile or desktop

jQuery Mobile or Desktop? As a web developer, I have had some experience with both jQuery Mobile and jQuery Desktop. Both frameworks have their pros and cons, and which one to use really depends on the specific project…

javascript1 min read
2023

node.js folder structure

Node.js Folder Structure If you are new to Node.js, it can be daunting to create a folder structure that will work for your project. The structure you choose will depend on the size and complexity of your project. Here…

javascript1 min read
ESC