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

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

How do I pass the value of an input type time to a Date object?

javascripthtmltime

提问by Arvin Flores

This function converts time to 12hr format, credits to a contributor on Stack Overflow for this function:

此函数将时间转换为 12 小时格式,感谢 Stack Overflow 上为此函数的贡献者:

JS

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());

HTML

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> 

My question is how do I get the value of the time input field to be displayed on the span tag in 12hr format. This code is semi-working.

我的问题是如何获取以 12 小时格式显示在跨度标签上的时间输入字段的值。这段代码是半工作的。

It displays the time in 12hr format but only displays the current time. The flow chart would be something like, user selects time in time input -> some JS to convert to 12hr format -> display as 12hr format in span tag. Any advice or suggestions?

它以 12 小时格式显示时间,但只显示当前时间。流程图类似于,用户在时间输入中选择时间 -> 一些 JS 转换为 12 小时格式 -> 在 span 标签中显示为 12 小时格式。任何意见或建议?

采纳答案by cн?dk

There's no need to use Dateand its methods the input is a Stringso you better use .split(":")method and you will get the hoursand minutesvalues directly.

没有必要使用Date它的方法,输入是一个,String所以你最好使用.split(":")方法,你会直接得到hoursminutes值。

Then just test if their values are lower than 10add a leading 0and if the hoursis higher than 12use pmsuffix or use amotherwise.

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

This is a live DEMO using onchange event of the time input with its value as parameter onchange="ampm(this.value):

这是一个使用时间输入的 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;
  }
}
<!--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>

回答by James Brierley

Your input value will be a string, not a date. I've set up a jsfiddlewhere I've modified your javascript to work on a string.

您的输入值将是一个字符串,而不是日期。我已经设置了一个jsfiddle,我已经修改了你的 javascript 以处理字符串。

$('#time').on('change', function() {
    var date = $('#time').val().split(':');

    var hours = date[0];
    var minutes = date[1];

    $('#display_time').text(ampm(hours, minutes));
});

function ampm(hours, minutes) {
    var ampm = hours >= 12 ? 'pm' : 'am';
    hours = hours % 12 || 12;
    minutes = minutes || 0;
    minutes = minutes < 10 ? '0'+minutes : minutes;
    return hours + ':' + minutes + ' ' + ampm;
}

回答by Mark Walters

Something like this will do it

像这样的事情会做

function showTime() {
    //Grab the time and split into hrs and mins
    var time = document.getElementById("time");
    if ( time.value === "")  {
        document.getElementById("mySpan").innerHTML = "";
        return false;
    }
    var hrs = time.value.split(":")[0];
    var mins = time.value.split(":")[1];
    var newTime = ampm(hrs, mins);
    document.getElementById("mySpan").innerHTML = newTime;
}

function ampm(hrs, mins) {
    return ( hrs % 12 || 12 ) + ":" + mins + (( hrs >= 12 ) ? "PM" : "AM" );
}

Hereis a an example. showTime()just needs to be ran onchange of the time input.

是一个例子。showTime()只需要在时间输入的变化上运行。