You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用JavaScript Date对象设置datetime-local类型HTML输入框的值

使用JavaScript给datetime-local类型的HTML输入框赋值并不简单,以下是几种尝试方法及遇到的问题:

input.valueAsNumber
document.getElementById("dateInput").valueAsNumber = new Date("Thu Mar 30 2023 12:54:17 GMT+0000 (UTC)").valueOf();

除非你处于UTC时区,否则这种方法行不通。valueAsNumber接受日期时间的数值形式,但不会将UTC的数值转换为本地时区对应的数值。

input.valueAsDate
document.getElementById("dateInput").valueAsDate = new Date("Thu Mar 30 2023 12:54:17 GMT+0000 (UTC)");

这种方法会抛出错误:

Uncaught DOMException: Failed to set the 'valueAsDate' property on 'HTMLInputElement': This input element does not support Date values.

input.value
document.getElementById("dateInput").value = "Thu Mar 30 2023 12:54:17 GMT+0000 (UTC)";

这种方法同样报错:

The specified value "Thu Mar 30 2023 12:54:17 GMT+0000 (UTC)" does not conform to the required format. The format is "yyyy-MM-ddThh:mm" followed by optional ":ss" or ":ss.SSS"

内容的提问来源于stack exchange,提问作者Bill Christo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.26 11:12:01