如何将输入类型时间的值传递给Date对象?

Arv*_*res 5 html javascript time html5

此函数将时间转换为12小时格式,在此函数上为Stack Overflow的贡献者提供信用:

JS

function ampm(date) {
    var hours = date.getHours();
    var minutes = date.getMinutes();
    var ampm = hours >= 12 ? 'pm' : 'am';
    hours = hours % 12;
    hours = hours ? hours : 12; // 0 should be 12
    minutes = minutes < 10 ? '0'+minutes : minutes; // if minutes less than 10, add a 0 in front of it ie: 6:6 -> 6:06
    var strTime = hours + ':' + minutes + ' ' + ampm;
    document.getElementById('time').value = strTime;
    return strTime;
}

////This is how the value of the time input is supposed to be displayed in 12 hr format
_("display_time").innerHTML = ampm(new Date());
Run Code Online (Sandbox Code Playgroud)

HTML

<!--This is the input field where a user selects a time-->
<input id="time" placeholder="Time" type="time" name="time" />




<!--This is where the value of the time input is supposed to be displayed in 12 hr format-->>
<span id="display_time"></span> 
Run Code Online (Sandbox Code Playgroud)

我的问题是如何获得时间输入字段的值以12hr格式显示在span标记上.此代码是半工作的.

它以12hr格式显示时间,但仅显示当前时间.流程图就像是,用户选择时间输入 - >一些JS转换为12hr格式 - >在span标签中显示为12hr格式.有什么建议或意见吗?

cнŝ*_*ŝdk 1

不需要使用Dateand 它的方法,输入是 a,String所以你最好使用.split(":")方法,你将直接获得hoursminutes值。

然后测试它们的值是否低于10添加前导0,是否hours高于12使用pm后缀或am以其他方式使用。

这是一个使用时间输入的 onchange 事件及其值作为参数的实时演示onchange="ampm(this.value)

function ampm(time) {

  console.log(time);
  if (time.value !== "") {
    var hours = time.split(":")[0];
    var minutes = time.split(":")[1];
    var suffix = hours >= 12 ? "pm" : "am";
    hours = hours % 12 || 12;
    hours = hours < 10 ? "0" + hours : hours;

    var displayTime = hours + ":" + minutes + " " + suffix;
    document.getElementById("display_time").innerHTML = displayTime;
  }
}
Run Code Online (Sandbox Code Playgroud)
<!--This is the input field where a user selects a time-->
<input id="time" placeholder="Time" type="time" name="time" onchange="ampm(this.value)" />
<span id="display_time"></span>
Run Code Online (Sandbox Code Playgroud)