使用 JavaScript 设置输入类型日期和时间的值

设置输入类型日期和时间的值

Set the Values of Input type Date and Time using JavaScript

value在 type 的输入元素上使用属性datetime
datetime-local设置它们的值。

value 属性可用于获取和设置输入类型的值
datetime以及datetime-local

这是示例的 HTML。

索引.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <title>bobbyhadz.com</title> </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>

我们创建了一个
输入类型: date、一个
输入类型: time和一个
输入类型: datetime-local

下面是显示如何设置和获取它们的值的 JavaScript 代码。

索引.js
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')))

设置值输入日期时间

这是一个很长的片段,但很大一部分代码是注释和辅助函数。

我们创建了一个可重用的函数,它接受一个Date对象并将其格式化为
YYYY-MM-DD hh:mm.

formatDate如果您想将日期格式设置为. YYYY-MM-DD hh:mm:ss

我们使用value每个输入的属性来设置datetime
datetime-local

  • 输入类型date需要一个格式为YYYY-MM-DD.

  • 输入类型time需要一个格式为hh:mmor的值hh:mm:ss

  • 输入类型datetime-local需要一个格式为
    YYYY-MM-DDThh:mm.

浏览器如何格式化输入字段取决于您的区域设置、操作系统等。但是,输入值将始终采用上述格式。

我们的formatDate职能:

  • 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.

设置值输入日期时间

# 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.

index.js
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.

设置值日期时间自定义日期

# 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.

index.html
<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:30.

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.

index.js
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.

用秒设置值日期时间

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: