将24小时时间转换为12小时时间的功能相当简单,但您有一些特殊要求。考虑以下几点:
// Convert string in 24 hour time to 12 hour hh:mm ap
// Input can be 12:23, 945, 09,12, etc.
function from24to12(s) {
var b = s.replace(/\D/g,'');
var h = b.substring(0, b.length - 2);
var m = b.substring(b.length - 2);
return (h%12 || 12) + ':' + m + ' ' + (h>11? 'PM':'AM');
}
console.log(from24to12('23:15')); // 11:15 PM
console.log(from24to12('015')); // 12:15 AM
console.log(from24to12('1.15')); // 1:15 AM
这里假设你不希望在小时和前导零的运营商将在两位数总是关键的几分钟,例如9.03,而不是9.3。为了支持后者,需要3行代码。
下支持分隔的任何字符,也说9.3上午9:03:
// Convert string in 24 hour time to 12 hour hh:mm ap
// Input can be 12:23, 945, 09,12, etc.
// Sseparator can be any non-digit. If no separator, assume [h]hmm
function from24to12(s) {
function z(n){return (n<10?'0':'')+n}
var h, m, b, re = /\D/;
// If there's a separator, split on it
// First part is h, second is m
if (re.test(s)) {
b = s.split(re);
h = b[0];
m = z(+b[1]);
// Otherwise, last two chars are mm, first one or two are h
} else {
h = s.substring(0, s.length - 2);
m = s.substring(s.length - 2);
}
return (h%12 || 12) + ':' + m + ' ' + (h>11? 'PM':'AM');
}
console.log(from24to12('23:15')); // 11:15 AM
console.log(from24to12('005')); // 12:05 AM
console.log(from24to12('1.15')); // 1:15 AM
console.log(from24to12('17.5')); // 5:05 PM
题外话(见codereview.stackexchange.com),你甚至没有张贴代码 – Alnitak
“下面的代码”在哪里? – RobG
此问题不是[*如何格式化javascript日期*]的重复(http://stackoverflow.com/questions/3552461/how-to-format-javascript-date)。没有涉及日期或日期对象,操作系统询问如何重新格式化代表时间的字符串。 – RobG