A function to convert 24 hr time to 12 hr time is fairly simple, however you have some peculiar requirements. Consider the following:
// 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
This assumes that you don't want leading zeros on the hour and that the operator will always key in two digits for the minutes, e.g. 9.03, not 9.3. To support the latter requires 3 more lines of code.
The following supports any character for a separator, and also say 9.3 for 9:03 AM:
// 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