📌  相关文章
📜  type time html 将 24 小时时间更改为 12 小时 - Html (1)

📅  最后修改于: 2023-12-03 14:48:03.946000             🧑  作者: Mango

HTML中将24小时时间更改为12小时

HTML中可以使用JavaScript来更改时间格式。我们可以使用<input type="time">来显示时间选择器,并使用JavaScript代码将选择的时间从24小时格式更改为12小时格式。

以下是如何使用HTML和JavaScript来实现此功能的示例代码:

<!DOCTYPE html>
<html>
<head>
  <script>
    function convertTo12HourFormat() {
      // 获取时间输入框的值
      var timeInput = document.getElementById("timeInput").value;

      // 将时间字符串转换为Date对象
      var time = new Date("2000-01-01T" + timeInput);

      // 将24小时格式转换为12小时格式
      var hours = time.getHours();
      var minutes = time.getMinutes();
      var ampm = hours >= 12 ? 'PM' : 'AM';
      
      hours = hours % 12;
      hours = hours ? hours : 12; // 将0转换为12
      
      // 更新时间输入框的值
      document.getElementById("timeOutput").value = hours + ':' + (minutes < 10 ? '0' + minutes : minutes) + ' ' + ampm;
    }
  </script>
</head>
<body>
  <label for="timeInput">请选择时间:</label>
  <input type="time" id="timeInput">

  <button onclick="convertTo12HourFormat()">转换为12小时格式</button>

  <br><br>

  <label for="timeOutput">转换结果:</label>
  <input type="text" id="timeOutput" readonly>
</body>
</html>

以上代码中,我们首先创建了一个<input type="time">作为时间选择器,并在其后添加了一个按钮,该按钮在单击时将时间从24小时格式转换为12小时格式。

在JavaScript代码中,convertTo12HourFormat()函数被调用以进行时间格式转换。首先,我们获取时间输入框的值并将其转换为Date对象。然后,我们分析小时部分以确定AM或PM,并将小时和分钟格式化为12小时格式。最后,我们将格式化后的时间更新到时间输出框。

希望以上代码对你有帮助!