Javascript:将 24 小时时间字符串转换为 12 小时时间(带 AM/PM,无时区)

标签 javascript time-format

服务器正在发送以下格式的字符串:18:00:00。这是一个独立于任何日期的时间值。如何在 Javascript 中将其转换为 6:00PM?我可以将今天的日期作为字符串添加到服务器发送的值之前,然后解析组合值,然后尝试 Date 对象的 .toTimeString() 方法,但 time 方法发出的格式是带有秒 block 的 24 小时时间。我可以编写一个函数,但是有内置的东西吗?

最佳答案

没有内置任何内容,我的解决方案如下:

function tConvert (time) {
  // Check correct time format and split into components
  time = time.toString ().match (/^([01]\d|2[0-3])(:)([0-5]\d)(:[0-5]\d)?$/) || [time];

  if (time.length > 1) { // If time format correct
    time = time.slice (1);  // Remove full string match value
    time[5] = +time[0] < 12 ? 'AM' : 'PM'; // Set AM/PM
    time[0] = +time[0] % 12 || 12; // Adjust hours
  }
  return time.join (''); // return adjusted time or original string
}

tConvert ('18:00:00');

此函数使用正则表达式来验证时间字符串并将其拆分为多个组成部分。还要注意,时间中的秒数可以选择性地省略。 如果提供了有效时间,则通过添加 AM/PM 指示并调整小时数来调整时间。

返回值是调整后的时间(如果存在有效时间)或原始字符串。

工作示例

(function() {

  function tConvert(time) {
    // Check correct time format and split into components
    time = time.toString().match(/^([01]\d|2[0-3])(:)([0-5]\d)(:[0-5]\d)?$/) || [time];

    if (time.length > 1) { // If time format correct
      time = time.slice(1); // Remove full string match value
      time[5] = +time[0] < 12 ? 'AM' : 'PM'; // Set AM/PM
      time[0] = +time[0] % 12 || 12; // Adjust hours
    }
    return time.join(''); // return adjusted time or original string
  }

  var tel = document.getElementById('tests');

  tel.innerHTML = tel.innerHTML.split(/\r*\n|\n\r*|\r/).map(function(v) {
    return v ? v + ' => "' + tConvert(v.trim()) + '"' : v;
  }).join('\n');
})();
<h3>tConvert tests : </h3>
<pre id="tests">
  18:00:00
  18:00
  00:00
  11:59:01
  12:00:00
  13:01:57
  24:00
  sdfsdf
  12:61:54
</pre>

关于Javascript:将 24 小时时间字符串转换为 12 小时时间(带 AM/PM,无时区),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13898423/

相关文章:

java - 如何重新格式化时间格式?

Java String.format 时间格式问题

javascript - 如何将 dom 元素 append 到另一个 dom 元素内,但位于 jquery 的第一个位置

javascript - 从页面 Angular 动态添加和删除类 7

javascript - 如何使用范围和导航器功能在 Highcharts 中创建列范围图表?

javascript - React Native 后台服务器启动报错

javascript - 转换格式yyyy-MM-ddTHH :mm:ss to datetime in javascript which is acceptable by getTime() function

go - 如何将 logrus 时间设置为 UTC

javascript - 在 jQuery 的 Deferred 对象中抛出错误