Javascript:使用AM/PM将24小时时间字符串转换为12小时时间,没有时区

Tim*_*Tim 26 javascript time-format

服务器以这种格式发送字符串:18:00:00.这是一个独立于任何日期的时间值.如何将其转换为6:00PMJavascript?我可以将今天的日期作为字符串添加到服务器发送的值,然后解析组合的值,然后尝试.toTimeString()Date对象的方法,但time方法发出的格式是24小时时间,带有秒块.我可以写一个函数,但内置了什么?

HBP*_*HBP 69

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

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');
Run Code Online (Sandbox Code Playgroud)

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

如果显示有效时间或原始字符串,则返回值是调整后的时间.

见jsFiddle:http://jsfiddle.net/ZDveb/


gil*_*ly3 22

要获取AM/PM,请检查小时部分是否小于12,然后是AM,否则为PM.

为了获得时间,做(hour % 12) || 12.

这应该这样做:

var timeString = "18:00:00";
var H = +timeString.substr(0, 2);
var h = H % 12 || 12;
var ampm = (H < 12 || H === 24) ? "AM" : "PM";
timeString = h + timeString.substr(2, 3) + ampm;
Run Code Online (Sandbox Code Playgroud)

http://jsfiddle.net/Skwt7/4/

这假设AM时间被格式化为例如08:00:00.如果它们的格式没有前导零,则必须测试第一个冒号的位置:

var hourEnd = timeString.indexOf(":");
var H = +timeString.substr(0, hourEnd);
var h = H % 12 || 12;
var ampm = (H < 12 || H === 24) ? "AM" : "PM";
timeString = h + timeString.substr(hourEnd, 3) + ampm;
Run Code Online (Sandbox Code Playgroud)

http://jsfiddle.net/Skwt7/3/


kva*_*aaz 13

使用momentjs会更好

只是从“下午 2 点”到“14 点”进行一点对话

const number = moment("02:00 PM", ["h:mm A"]).format("HH:mm");
cosole.log(number); 
Run Code Online (Sandbox Code Playgroud)

//“14.00”“14.00”到“下午 2 点”

const number = moment("14.00", ["HH.mm"]).format("hh:mm a");
cosole.log(number); // "02:00 pm"
Run Code Online (Sandbox Code Playgroud)


bbs*_*nbb 9

toLocaleTimeString()使此操作非常简单。无需自己执行此操作。如果您不使用字符串方法攻击日期,那么您会更快乐,寿命更长。

const timeString = '18:00:00'
// Append any date. Use your birthday.
const timeString12hr = new Date('1970-01-01T' + timeString + 'Z')
  .toLocaleTimeString({},
    {timeZone:'UTC',hour12:true,hour:'numeric',minute:'numeric'}
  );
document.getElementById('myTime').innerText = timeString12hr
Run Code Online (Sandbox Code Playgroud)
<h1 id='myTime'></h1>
Run Code Online (Sandbox Code Playgroud)


Dan*_*lov 9

简短的 ES6 代码

const convertFrom24To12Format = (time24) => {
  const [sHours, minutes] = time24.match(/([0-9]{1,2}):([0-9]{2})/).slice(1);
  const period = +sHours < 12 ? 'AM' : 'PM';
  const hours = +sHours % 12 || 12;

  return `${hours}:${minutes} ${period}`;
}
Run Code Online (Sandbox Code Playgroud)
const convertFrom12To24Format = (time12) => {
  const [sHours, minutes, period] = time12.match(/([0-9]{1,2}):([0-9]{2}) (AM|PM)/).slice(1);
  const PM = period === 'PM';
  const hours = (+sHours % 12) + (PM ? 12 : 0);

  return `${('0' + hours).slice(-2)}:${minutes}`;
}
Run Code Online (Sandbox Code Playgroud)


Hug*_*ugo 6

基于gilly3的答案。

如果要转换:

 08:00 to 08:00 AM 
 16:00 to 04:00 PM
Run Code Online (Sandbox Code Playgroud)

然后这将起作用:

function tConv24(time24) {
  var ts = time24;
  var H = +ts.substr(0, 2);
  var h = (H % 12) || 12;
  h = (h < 10)?("0"+h):h;  // leading 0 at the left for 1 digit hours
  var ampm = H < 12 ? " AM" : " PM";
  ts = h + ts.substr(2, 3) + ampm;
  return ts;
};
Run Code Online (Sandbox Code Playgroud)

https://jsfiddle.net/fpjs9g0L/


akh*_*hal 6

一个简单的代码是

time = time.split(':');// here the time is like "16:14"
let meridiemTime = time[0] >= 12 && (time[0]-12 || 12) + ':' + time[1] + ' PM' || (Number(time[0]) || 12) + ':' + time[1] + ' AM';
Run Code Online (Sandbox Code Playgroud)

您可以根据您的时间格式进行调整


小智 6

通过使用 Moment 库,我们可以将 24 小时时间格式转换为 12 小时格式。

moment('20:00', 'hh:mm').format('hh:mm')
Run Code Online (Sandbox Code Playgroud)

//// 输出:08:00

如果你想转换成AM和PM

moment('20:00', 'hh:mm a').format('hh:mm a')
Run Code Online (Sandbox Code Playgroud)

//// 输出:晚上 08:00


Lou*_*nAL 5

在研究同一个问题时,我遇到了几个复杂、难以理解的解决方案,然后我突然明白了:有一个非常简单的解决方案,它不依赖于难以阅读的正则表达式或其他复杂的代码。除非我遗漏了一些明显的东西,否则这是一个非常简单、易于理解的解决方案:

function timeTo12HrFormat(time)
{   // Take a time in 24 hour format and format it in 12 hour format
    var time_part_array = time.split(":");
    var ampm = 'AM';

    if (time_part_array[0] >= 12) {
        ampm = 'PM';
    }

    if (time_part_array[0] > 12) {
        time_part_array[0] = time_part_array[0] - 12;
    }

    formatted_time = time_part_array[0] + ':' + time_part_array[1] + ':' + time_part_array[2] + ' ' + ampm;

    return formatted_time;
}



var time = timeTo12HrFormat(18:00:00);
console.log(time);  // 6:00:00 PM
Run Code Online (Sandbox Code Playgroud)