Javascript:使用AM / PM将24小时时间字符串转换为12小时时间,没有时区 [英] Javascript: convert 24-hour time-of-day string to 12-hour time with AM/PM and no timezone

查看:170
本文介绍了Javascript:使用AM / PM将24小时时间字符串转换为12小时时间,没有时区的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

The server is sending a string in this format: 18:00:00. This is a time-of-day value independent of any date. How to convert it to 6:00PM in Javascript? I could prepend today's date as a string to the value sent by the server and then parse the combined values and then try the .toTimeString() method of the Date object, but the format that time method emits is 24-hour time with a seconds chunk. I could write a function, but is there something built in?

推荐答案

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

Nothing built in, my solution would be as follows :

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指示并调整小时数进行调整。

This function uses a regular expression to validate the time string and to split it into its component parts. Note also that the seconds in the time may optionally be omitted. If a valid time was presented, it is adjusted by adding the AM/PM indication and adjusting the hours.

如果出现有效时间或原始字符串,则返回值是调整后的时间。

The return value is the adjusted time if a valid time was presented or the original string.

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

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

这篇关于Javascript:使用AM / PM将24小时时间字符串转换为12小时时间,没有时区的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆