如何使用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
相关产品推荐
相关产品推荐

