【问题标题】:Why my time is not showing correct output when submitting?为什么我的时间在提交时没有显示正确的输出?
【发布时间】:2020-10-11 04:56:12
【问题描述】:

我正在使用以下代码。一切都很好,但是当我发送信息时,它会以 24 小时格式发送。 我该如何解决这个问题?现在显示13:00 我想显示1:00 PM

  <!DOCTYPE html>
  <html>
<head>
  <title>Page Title</title>
</head>
<body>
  <input type="time" value=""  id="a_time">
  <input type="button" onclick="gettime();" value="Click Here">
  <script type="text/javascript">
    function gettime(){
      alert(document.getElementById("a_time").value);
    }
  </script>
</body>
  </html>

【问题讨论】:

  • HTML 5 输入显示在用户的区域设置中,但使用 ISO 格式提交。日期以 Y-m-d 形式发送,时间为 24 小时制 H:m:s,数字使用 . 作为小数分隔符...

标签: javascript html typescript html-input


【解决方案1】:

这是上一个答案的另一种方法,它使用模板文字字符串,使事情更简洁,更容易理解。

这个想法是,您首先需要自己获取时间的小时部分并将其转换为整数。接下来,您需要编写逻辑来检查该数字是否大于 12 以检查它是否是 PM(并且还检查当数字是午夜的 0 或中午的 12 时的极端情况)。如果是午夜或中午,则返回 12。超过 12,取余数 mod 12。否则,按原样返回小时数。按原样附上会议记录,然后添加上午或下午:

<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>
<input type="time" value=""  id="a_time">
<input type="button" onclick="gettime();" value="Click Here">
<script type="text/javascript">
  function formatTime(timeStr) {
      const hours = timeStr.substring(0, 2);
      const mins = timeStr.substring(3, 5);
    
      const isTwelve = parseInt(hours) === 0 || parseInt(hours) === 12;
      const isPM = parseInt(hours) >= 12;

      return `${isTwelve ? "12" : isPM ? `0${parseInt(hours) % 12}` : hours}:${mins} ${isPM ? "PM" : "AM"}`
  }
  function gettime(){
      const formattedTime = formatTime(document.getElementById("a_time").value);
      alert(formattedTime);
  }
</script>
</body>
</html>

【讨论】:

    【解决方案2】:

    这就是你应该得到的。

    这个问题的答案是所谓的24 hour format就是它所假设的应用,官方命名为valid time string,你可以在HTML 5.2:2 section看到

    【讨论】:

      【解决方案3】:

      试试这个,

      <!DOCTYPE html>
      <html>
      <head>
      <title>Page Title</title>
      </head>
      <body>
      
      <input type="time" value=""  id="a_time">
      <input type="button" onclick="gettime();" value="Click Here">
      <script type="text/javascript">
      function gettime(){
          var v = document.getElementById("a_time").value;
          var r = tConvert (v);
          alert(r);
      }
      
      
      function tConvert (time) {
      
            time = time.toString ().match (/^([01]\d|2[0-3])(:)([0-5]\d)(:[0-5]\d)?$/) || [time];
          
            if (time.length > 1) {
              time = time.slice (1); 
              time[5] = +time[0] < 12 ? 'AM' : 'PM'; 
              time[0] = +time[0] % 12 || 12; 
            }
            return time.join (''); 
      }
      </script>
      </body>
      </html>
      

      【讨论】:

        猜你喜欢
        • 2019-11-13
        • 2021-10-06
        • 2021-07-13
        • 2012-12-27
        • 1970-01-01
        • 2021-03-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多