Javascript 从 HTML 时间输入获取 AM/PM

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

Get AM/PM from HTML time input

javascripthtml

提问by SamSmith

First, I know that <input type="time">is not supported by IE10 or earlier, and Firefox, but this is only for testing purposes and I will make appropriate, cross-browser changes at another time.

首先,我知道<input type="time">IE10 或更早版本和 Firefox 不支持,但这仅用于测试目的,我将在其他时间进行适当的跨浏览器更改。

For the time being, I have a HTML time input field. I am trying to extract the values from it including the hour, minutes and AM/PM. I can display the hour and minutes, but an AM/PM indication is not including.

目前,我有一个 HTML 时间输入字段。我试图从中提取值,包括小时、分钟和 AM/PM。我可以显示小时和分钟,但不包括 AM/PM 指示。

I have an input as follows:

我有一个输入如下:

<input type="time" name="end-time" id="end-time">

<input type="time" name="end-time" id="end-time">

I print out via alert()the input value as follows:

我通过alert()输入值打印如下:

alert(document.getElementById('end-time').value);

alert(document.getElementById('end-time').value);

Upon input I receive an alert such as:

输入后,我收到警报,例如:

01:34.

01:34.

Notice that an AM/PM is not included in the alert().

请注意,AM/PM 不包含在alert().

How can I get the AM/PM value from a HTML time input via Javascript?

如何通过 Javascript 从 HTML 时间输入中获取 AM/PM 值?

回答by Nikhilesh Shivarathri

As far as i know, We cannot get the value from the input directly in the meridian format of 'AM/PM'. Instead, we can write our own logic of converting the value in the AM/PM format and store/display it.

据我所知,我们无法以“AM/PM”的子午线格式直接从输入中获取值。相反,我们可以编写自己的逻辑,将值转换为 AM/PM 格式并存储/显示它。

Below is the implementation of it.

下面是它的实现。

var inputEle = document.getElementById('timeInput');


function onTimeChange() {
  var timeSplit = inputEle.value.split(':'),
    hours,
    minutes,
    meridian;
  hours = timeSplit[0];
  minutes = timeSplit[1];
  if (hours > 12) {
    meridian = 'PM';
    hours -= 12;
  } else if (hours < 12) {
    meridian = 'AM';
    if (hours == 0) {
      hours = 12;
    }
  } else {
    meridian = 'PM';
  }
  alert(hours + ':' + minutes + ' ' + meridian);
}
<input type="time" onchange="onTimeChange()" id="timeInput" />

回答by StardustGogeta

function print() {
  t = document.getElementById('time').value
  var [h,m] = t.split(":");
  console.log((h%12+12*(h%12==0))+":"+m, h >= 12 ? 'PM' : 'AM');
}
<input type="time" id="time">
<button onclick="print()">Submit</button>

Does this work for you?

这对你有用吗?

回答by ericornelissen

You could try using document.getElementById('end-time').valueAsDatewhich gives you a new Date() with the correct time. From there you can get the hours using .getHours()(0-23) and minutes using .getMinutes()(0-59). See thisfor more about JavaScript Dates.

您可以尝试使用document.getElementById('end-time').valueAsDatewhich 为您提供具有正确时间的 new Date() 。从那里您可以使用.getHours()(0-23)获取小时数,使用.getMinutes()(0-59)获取分钟数。见为更多关于JavaScript日期。

回答by James Walker

Here's a fix for date AND time.

这是日期和时间的修复。

<!DOCTYPE HTML >
<html>
<head>
<title>12 hour Time and Date stamp</title>
<meta name="" content="">
<script>
///////////
///////// DATE generator    /////////
function date_time(id){
        date = new Date;
        year = date.getFullYear();
        month = date.getMonth();
        months = new Array('Jan', 'Feb', 'Mar', 'Apr', 'May', 'June', 'July', 'Aug', 'Sept', 'Oct', 'Nov', 'Dec');
        d = date.getDate();
        day = date.getDay();
        days = new Array('Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday');
        h = date.getHours();
        if(h<10){h = "0"+h;}
      m = date.getMinutes();
        if(m<10){m = "0"+m;}
       s = date.getSeconds();
        if(s<10){s = "0"+s;}
       result = ''+days[day]+' '+months[month]+' '+d+' '+year;
        document.getElementById(id).innerHTML = result;
        setTimeout('date_time("'+id+'");','1000');
        return true;
}
///////// end DATE Generator /////////
//////////////////////////////////////
/////////// Time Generator ///////////
function tS(){ x=new Date(); x.setTime(x.getTime()); return x; } 
function lZ(x){ return (x>9)?x:'0'+x; } 
function tH(x){ if(x==0){ x=12; } return (x>12)?x-=12:x; } 
function dT(){ if(fr==0){ fr=1; document.write('<font size=3 face=Arial><b><span id="tP">'+eval(oT)+'</span></b></font>'); } document.getElementById('tP').innerHTML=eval(oT); setTimeout('dT()',1000); } 
function aP(x){ return (x>11)?'pm':'am'; } 
var fr=0,oT="' '+tH(tS().getHours())+':'+lZ(tS().getMinutes())+':'+lZ(tS().getSeconds())+' '+aP(tS().getHours())";
///////// end Time Generator /////////
/////////
</script>
</head>

<body>
<!--Date.. Easily adjustable with javascript Array-->
<p><span id="date_time"></span></p>
    <script type="text/javascript">window.onload = date_time('date_time');</script><!--this MUST be included for Date-->
<!--Time in 12 hour format-->
<p><span id="dT"><script language="JavaScript">window.onload = dT('dT');</script></span></p>
</body>
</html> 

I have used this for over 6 years. ALWAYS works. But a couple notes:

1: For the time, adjust the CSS from within the Javascript.
2:Adjust display text (jan,Feb,march... mon,tues,wed,etc...) By changing values within Date Generator Section.

You can see this working at AutoRoXX Network

Hopefully this code snip will help you with what you are trying to accomplish.
I HATE seeing people struggle :-)

我已经使用这个超过 6 年了。总是有效。但有几个注意事项:

1:暂时,从 Javascript 中调整 CSS。
2:通过更改日期生成器部分中的值来调整显示文本(一月、二月、三月... mon、tues、wed 等...)。

您可以在AutoRoXX Network 上看到这个工作

希望这个代码片段能帮助您完成您想要完成的工作。
我讨厌看到人们挣扎:-)

回答by guest271314

Do not believe accessing .shadowRootof native <input>elements using DOMmethods is currently possible. Where, at chromium, chrome the element

不要相信使用方法访问.shadowRoot本机<input>元素DOM目前是可能的。哪里,在铬,铬元素

<span 
  role="spinbutton" 
  aria-valuetext="blank" 
  aria-valuemin="1" 
  aria-valuemax="2" 
  aria-help="AM/PM" 
  pseudo="-webkit-datetime-edit-ampm-field">
--
</span>

having .innerHTMLof AMor PMis rendered at <input type="time">element .shadowRootat changeevent of element. See Is it possible to access Shadow DOM elements through the parent document?.

具有.innerHTMLAMPM在呈现<input type="time">元件.shadowRootchange元件的事件。请参阅是否可以通过父文档访问 Shadow DOM 元素?.

Have not found a workaround to select the elements within the .shadowRootof DOM` element,

还没有找到一个解决方法中选择元素.shadowRootDOM'元素,

You can use input.valueAsDate.getTime(), which is incremented in values of 3600000, where is value is less than 43200000the time is "AM", else "PM"; format the output by checking if first two digits of .valueis greater than or equal to 13, if true replace first two digits of .valuestring with value of an object having property names ranging from 13through 23

您可以使用input.valueAsDate.getTime(), 以 的值递增3600000,其中值小于43200000时间"AM",否则"PM";通过检查 的前两位数字.value是否大于或等于 来格式化输出13,如果为真,则将.value字符串的前两位数字替换为具有属性名称范围从13到的对象的值23

var times = {}, re = /^\d+(?=:)/;

for (var i = 13, n = 1; i < 24; i++, n++) {
  times[i] = n < 10 ? "0" + n : n
}

document.getElementById("end-time")
.onchange = function() {
  var time = this
  , value = time.value
  , match = value.match(re)[0];
  this.nextElementSibling.innerHTML =
  (match && match >= 13 ? value.replace(re, times[match]) : value)
  + (time.valueAsDate.getTime() < 43200000 ? " AM" : " PM")
}
<input type="time" name="end-time" id="end-time">
<label for="end-time"></label>