使用 Javascript 在 HTML5 时间字段中输入时间

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13459368/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 18:50:39  来源:igfitidea点击:

Using Javascript to input time in HTML5 time field

javascripthtmltimeinput

提问by Envious

I'm trying to create a function in JS that will fill in the html5 <input type=time>with a format like this hh:mm:ss.

我正在尝试在 JS 中创建一个函数,它将<input type=time>用这样的格式填充 html5 hh:mm:ss

function timeChange(){
var d = new Date();
d.getHours();
d.getMinutes();
d.getSeconds();

var hours = d.getHours();
var minutes = d.getMinutes();
var seconds = d.getSeconds();

document.getElementById("time_in").value = (....);
}

I'm not sure how to code the .value for this. I've tried using .value = (hours":"minutes":"seconds);but that just gives me a compile error.

我不确定如何为此编码 .value。我试过使用,.value = (hours":"minutes":"seconds);但这只会给我一个编译错误。

Anyone got ideas? I just need it in hh:mm:ss.

有人有想法吗?我只需要它在 hh:mm:ss 中。

HTML5 code:

HTML5 代码:

 <button type="button" onClick="timeChange()">Time</button>

 <input id="time_in" type="time" name="time_in">

回答by freejosh

hours":"minutes":"secondsisn't concatenating the string, you need +s: hours+":"+minutes+":"+seconds

hours":"minutes":"seconds不是连接字符串,你需要+s:hours+":"+minutes+":"+seconds

回答by int32_t

var d = new Date();
// Need to create UTC time of which fields are same as local time.
d.setUTCHours(d.getHours(), d.getMinutes(), d.getSeconds(), 0);
document.getElementById("time_in").valueAsDate = d;

回答by Ryan

document.getElementById('time_in').value = hours + ":" + minutes + ":" + seconds;

Otherwise you're not creating one concatenated string.

否则,您不会创建一个连接字符串。

回答by Shmiddty

The simplest way would be to grab the time string from the Date object:

最简单的方法是从 Date 对象中获取时间字符串:

var time = (new Date()).toTimeString().split(' ')[0];

var time = (new Date()).toTimeString().split(' ')[0];

The split allows us to remove the timezone portion of the string.

拆分允许我们删除字符串的时区部分。