更新时间:2023-02-26 16:03:02
没有内置的,我的解决方案如下:
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/