将 javascript 日期分配给 html5 datetime-local 输入
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28760254/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
assign javascript date to html5 datetime-local input
提问by Alexander Taylor
DOM:
DOM:
<input id="myTextbox" type="datetime-local" />
Javascript (jQuery):
Javascript (jQuery):
$('#myTextbox').val(new Date().toISOString());
Doesn't work. The format of input[type=datetime-local] is supposed to be ISO 8601, which is what javascript's Date.toISOString() returns.
不起作用。input[type=datetime-local] 的格式应该是 ISO 8601,这是 javascript 的 Date.toISOString() 返回的格式。
采纳答案by int32_t
Use $('#myTextbox')[0].valueAsNumber = new Date().getTime()
.
使用$('#myTextbox')[0].valueAsNumber = new Date().getTime()
.
HTMLInputElement
interface also has valueAsDate
property, but type=datetime-local
doesn't support it unfortunately.
HTMLInputElement
interface 也有valueAsDate
属性,但type=datetime-local
不幸的是不支持它。
回答by Alexander Taylor
http://www.w3schools.com/jsref/jsref_toisostring.asp:
http://www.w3schools.com/jsref/jsref_toisostring.asp:
The toISOString() method converts a Date object into a string, using the ISO standard.
The standard is called ISO-8601 and the format is: YYYY-MM-DDTHH:mm:ss.sssZ
toISOString() 方法使用 ISO 标准将 Date 对象转换为字符串。
该标准称为 ISO-8601,格式为:YYYY-MM-DDTHH:mm:ss.sssZ
While ISO 8601 has some flexibility, the format of javascript's Date's toISOString() is exactly as shown above.
虽然 ISO 8601 具有一定的灵活性,但 javascript 的 Date 的 toISOString() 的格式与上面显示的完全一样。
The 'Z' at the end means this is a UTC date. So, this representation includes timezone information. (Javascript dates are naturally in UTC time since they are internally represented as milliseconds since epoch.)
末尾的“Z”表示这是 UTC 日期。因此,此表示包括时区信息。(Javascript 日期自然是 UTC 时间,因为它们在内部表示为自纪元以来的毫秒数。)
The format of HTML5 input with type=datetime-local must be ...
type=datetime-local 的 HTML5 输入格式必须是 ...
The following parts, in exactly the following order:
- A date.
- The literal string "T".
- A time.
Example:
1985-04-12T23:20:50.52
1996-12-19T16:39:57
以下部分,完全按照以下顺序:
- 一个约会。
- 文字字符串“T”。
- 一个时间。
例子:
1985-04-12T23:20:50.52
1996-12-19T16:39:57
http://www.w3.org/TR/html-markup/input.datetime-local.html
http://www.w3.org/TR/html-markup/input.datetime-local.html
This is still ISO 8601, but stricter, and it does not allow a timezone to be specified.
这仍然是 ISO 8601,但更严格,并且不允许指定时区。
Luckily, removing the timezone is as easy as removing the trailing 'Z'.
幸运的是,删除时区就像删除尾随的“Z”一样简单。
var isoStr = new Date().toISOString();
$('#myTextbox').val(isoStr.substring(0,isoStr.length-1));