Javascript input date set value

Input Date value Property

The value property sets or returns the value of the value attribute of a date field. The value attribute specifies a date for the date field.

Browser Support

Property
value Yes 12.0 Yes Yes Yes

Note: does not show as a proper date field in IE11, and earlier.

Syntax

Property Values

Value Description
YYYY-MM-DD Specifies a date for the date field.

Technical Details

More Examples

Example

Get the date of a date field:

Example

An example that shows the difference between the defaultValue and value property:

Unlock Full Access 50% off

COLOR PICKER

colorpicker

Join our Bootcamp!

Report Error

If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:

Thank You For Helping Us!

Your message has been sent to W3Schools.

Top Tutorials
Top References
Top Examples
Get Certified

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.

Источник

Javascript input date set value

Last updated: Jan 11, 2023
Reading time · 4 min

banner

# Set the Values of Input type Date and Time

Use the value property on the input elements of type date , time and datetime-local to set their values.

The value property can be used to get and set the value of an input type date , time and datetime-local .

Here is the HTML for the examples.

Copied!
DOCTYPE html> html lang="en"> head> meta charset="UTF-8" /> title>bobbyhadz.comtitle> head> body> label for="start">Input type Date:label> input type="date" id="date" name="trip-start" /> br />br /> label for="appt">Input type Time:label> input type="time" id="time" name="appt" /> br />br /> label for="meeting-time">Input type Datetime-local:label> input type="datetime-local" id="datetime-local" name="meeting-time" /> script src="index.js"> script> body> html>

Here is the JavaScript code that shows how to set and get their values.

Copied!
const [date, time] = formatDate(new Date()).split(' '); console.log(date); // 👉️ 2021-12-31 console.log(time); // 👉️ 09:43 // ✅ Set Date input Value const dateInput = document.getElementById('date'); dateInput.value = date; // 👇️️ "2021-12-31" console.log('dateInput value: ', dateInput.value); // ------------------------------------------------ // ✅ Set time input value const timeInput = document.getElementById('time'); timeInput.value = time; // 👇️ "09:43" console.log('timeInput value: ', timeInput.value); // ------------------------------------------------ // ✅ Set datetime-local input value const datetimeLocalInput = document.getElementById('datetime-local'); datetimeLocalInput.value = date + 'T' + time; // 👇️ "2021-12-31T10:09" console.log('dateTimeLocalInput value: ', datetimeLocalInput.value); // 👇️👇️👇️ Format Date as yyyy-mm-dd hh:mm:ss // 👇️ (Helper functions) function padTo2Digits(num) return num.toString().padStart(2, '0'); > function formatDate(date) return ( [ date.getFullYear(), padTo2Digits(date.getMonth() + 1), padTo2Digits(date.getDate()), ].join('-') + ' ' + [ padTo2Digits(date.getHours()), padTo2Digits(date.getMinutes()), // padTo2Digits(date.getSeconds()), // 👈️ can also add seconds ].join(':') ); > // 👇️ 2022-07-22 08:50:39 console.log(formatDate(new Date())) // 👇️ 2025-05-04 05:24 console.log(formatDate(new Date('May 04, 2025 05:24:07')))

set values input date time

It’s quite a long snippet, but a good chunk of the code is comments and helper functions.

We created a reusable function that takes a Date object and formats it as YYYY-MM-DD hh:mm .

You can optionally uncomment the line that adds the seconds towards the end of the formatDate function if you want to format the date as YYYY-MM-DD hh:mm:ss .

We used the value property on each of the inputs to set the date , time and datetime-local values.

  • The input type date expects a value in the format of YYYY-MM-DD .
  • The input type time expects a value in the format of hh:mm or hh:mm:ss .
  • The input type datetime-local expects a value in the format of YYYY-MM-DDThh:mm .

How the browser formats the input fields depends on your locale, operating system, etc. However, the input values will always be of the aforementioned formats.

  • reads the year, month, date, hours, minutes and seconds (optionally) from the passed in Date object
  • pads the digits with a leading zero if, for example, the hours or minutes are less than 10

We need to handle the scenario where the month, day, hours, minutes or seconds values will be less than 10 and produce consistent output.

Here is a screenshot of how the input fields look on my machine. I’m in the EU and I’m on Linux.

set values input date time

# Setting the input values to a time in the future

Note that you don’t have to set the input values to the current date and time. The formatDate function takes a Date object that you can set to a date and time in the future or the past.

Here is an example that passes a future Date and time — 2035-05-04 05:24 to the method.

Copied!
const [date, time] = formatDate(new Date('May 04, 2035 05:24')).split(' '); console.log(date); // 👉️ 2035-05-04 console.log(time); // 👉️ 05:24 // ✅ Set Date input Value const dateInput = document.getElementById('date'); dateInput.value = date; console.log('dateInput value: ', dateInput.value); // 👉️ "2035-05-04" // ✅ Set time input value const timeInput = document.getElementById('time'); timeInput.value = time; console.log('timeInput value: ', timeInput.value); // 👉️ "05:24" // ✅ Set datetime-local input value const datetimeLocalInput = document.getElementById('datetime-local'); datetimeLocalInput.value = date + 'T' + time; // 👇️ "2035-05-04T05:24" console.log('dateTimeLocalInput value: ', datetimeLocalInput.value); // 👇️ Format Date as yyyy-mm-dd hh:mm:ss function padTo2Digits(num) return num.toString().padStart(2, '0'); > function formatDate(date) return ( [ date.getFullYear(), padTo2Digits(date.getMonth() + 1), padTo2Digits(date.getDate()), ].join('-') + ' ' + [ padTo2Digits(date.getHours()), padTo2Digits(date.getMinutes()), // padTo2Digits(date.getSeconds()), // 👈️ can also add seconds ].join(':') ); > // 👇️ 2022-07-22 08:50:39 console.log(formatDate(new Date())) // 👇️ 2035-05-04 05:24 console.log(formatDate(new Date('May 04, 2035 05:24:07')))

And here is what the browser output looks like.

set values date time custom date

# Checking if your input field has constraints

If you have difficulties setting the date and time values programmatically, you first want to check your formatting, and then check if the input fields have constraints, e.g. max or min value.

Copied!
input type="date" id="date" name="trip-start" min="2021-01-01" max="2021-12-31" />

The input field above has a constraint for the min and max specified Dates .

If you click on the input in your browser it wouldn’t allow you to select a date out of the specified range.

While you might be able to set a different value programmatically, it’s something to keep in mind.

Another thing to note is that if you submit the time using an HTTP GET request, the colon character needs to be escaped when included in the URL parameters, e.g. time=2021-12-31T08%3A30 .

You can use the encodeURI() function to encode a URI and replace the colon with an escape sequence of UTF-8 encoded characters.

# Setting the seconds of the time and datetime-local inputs

Here is an example that sets the seconds of the time and datetime-local inputs.

Copied!
const [date, time] = formatDate(new Date()).split(' '); console.log(date); // 👉️ "2022-07-22" console.log(time); // 👉️ "08:49:16" // ✅ Set Date input Value const dateInput = document.getElementById('date'); dateInput.value = date; // 👇️ "2022-07-22" console.log('dateInput value: ', dateInput.value); // -------------------------------------------------- // ✅ Set time input value const timeInput = document.getElementById('time'); timeInput.value = time; // 👇️ "08:49:16" console.log('timeInput value: ', timeInput.value); // -------------------------------------------------- // ✅ Set datetime-local input value const datetimeLocalInput = document.getElementById('datetime-local'); datetimeLocalInput.value = date + 'T' + time; // 👇️ "2022-07-22T08:49:21" console.log('dateTimeLocalInput value: ', datetimeLocalInput.value); // 👇️ Format Date as yyyy-mm-dd hh:mm:ss function padTo2Digits(num) return num.toString().padStart(2, '0'); > function formatDate(date) return ( [ date.getFullYear(), padTo2Digits(date.getMonth() + 1), padTo2Digits(date.getDate()), ].join('-') + ' ' + [ padTo2Digits(date.getHours()), padTo2Digits(date.getMinutes()), padTo2Digits(date.getSeconds()), ].join(':') ); > // 👇️ 2022-07-22 08:50:39 console.log(formatDate(new Date())); // 👇️ 2025-05-04 05:24:07 console.log(formatDate(new Date('May 04, 2035 05:24:07')));

And here is how the output with seconds looks in my browser.

set values date time with seconds

All we did is uncomment the line that grabs the seconds from the Date object in the formatDate function.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.

Источник

How To Set The Values Of Input Type Date And Time Using JavaScript?

Set the Values of Input type Date and Time using JavaScript

Input date and input time are commonly used for registration forms. If you need to set the values of Input type Date and Time using JavaScript for your website, read this article, we will show you the simplest ways to do it.

Set the values of input type Date and Time using JavaScript?

Before we start setting input date and time values, let’s quickly look at their concepts.

Input type date: generates input fields that allow the user to enter a date. Its value includes the day, month, and year but not the time.

Input type time: generates input fields that allow the user to enter a time (hours, minutes). Its value includes only the time, not the date.

Now, let’s set the values for them.

Using the value attribute

Any input tag has a value attribute, so we can use this attribute to set the value for the input Date and input Time.

First, we need to get the input Date and input Time tags. Then call the value attribute on each tag and set the value for them. We can either hard set a value or set the current time value using the Date() constructor. Note that the format accepted in these two input tags must have a ‘0’ in front of numbers less than 10.

See the example below to understand better.

Hello, this is LearnShareIT
Date:
Time:
// Get input Date and input Time const dateInput = document.getElementById('date-input'); const timeInput = document.getElementById('time-input'); // Get the current date let now = new Date(); let date = now.getDate(); let month = now.getMonth(); let year = now.getFullYear(); // Format dates and months < 10 if (date < 10) date = '0' + date; if (month < 10) month = '0' + month; // Get the current time let hour = now.getHours(); let min = now.getMinutes(); // Format hours and minutes < 10 if (hour < 10) hour = '0' + hour; if (min < 10) min = '0' + min; // Set value for input Date and input Time using the value attribute dateInput.value = `$-$-$`; // 'YYYY-MM-DD' timeInput.value = `$:$`; // 'HH:MM'

Using the setAttribute() function

You can read more about the syntax of setAttribute() here before we start coding.

In addition to directly setting the value attribute of the input tag, we can also use the setAttribute() function to indirectly set the value for the input Date and input Time. Just pass the string ‘value’ into the first argument and the date value or time value on the 2nd argument.

This time let’s gather the code to get the current date and format the date into a function for reuse. Then use setAttribute() to set the value for the input Date and input Time.

// Get input Date and input Time const dateInput = document.getElementById('date-input'); const timeInput = document.getElementById('time-input'); // Generate a formatted date and time object. function createFormattedCurrentDatetime() < // Get the current date let now = new Date(); let date = now.getDate(); let month = now.getMonth(); let year = now.getFullYear(); // Format date and month < 10 if (date < 10) date = '0' + date; if (month < 10) month = '0' + month; // Get the current time let hour = now.getHours(); let min = now.getMinutes(); // Format hours and minutes < 10 if (hour < 10) hour = '0' + hour; if (min < 10) min = '0' + min; return < date: `$-$-$`, time: `$:$` >; > // Set value for input Date and input Time using setAttribute() let date = createFormattedCurrentDatetime().date; dateInput.setAttribute('value', date); let time = createFormattedCurrentDatetime().time; timeInput.setAttribute('value', time);

Summary

Above, we have shown you two ways that are considered best practices to set the values of input type Date and Time using JavaScript. You don’t have to use both ways. Just choose the one that works best for you. If you have any questions, please comment below.

Maybe you are interested:

Hi, I’m Cora Lopez. I have a passion for teaching programming languages such as Python, Java, Php, Javascript … I’m creating the free python course online. I hope this helps you in your learning journey.

Name of the university: HCMUE
Major: IT
Programming Languages: HTML/CSS/Javascript, PHP/sql/laravel, Python, Java

Источник

Читайте также:  Javascript угол между двумя векторами
Оцените статью