Mostly so I can find this again when I need it:
function formatTime(t) {
var myTime = t.value;
var badFormat = "Bad format";
// Ensure we have a value
if (myTime == "") {
return(true);
}
var regexSplit = /\s+/;
var regexTime = /:/;
var regexMili = /^([0-1][0-9]|2[0-3]):[0-5][0-9]$/; // 00:00 to
23:59
var regexHour = /^(0?[1-9]|1[0-2])$/;
var regexMin = /^[0-5][0-9]$/;
var regexAm = /^[aA]/;
var regexPm = /^[pP]/;
// split value into atoms
var atoms = t.value.split(regexSplit);
// If there is only one atom, are we using military time?
if ( (atoms.length) == 1) {
var timeAtom = atoms[0];
if (! regexMili.test(timeAtom) ) {
t.value = badFormat;
t.focus();
t.select();
return;
}
// Split time into hours, minutes
timeAtoms = timeAtom.split(regexTime);
var hours = parseInt(timeAtoms[0]);
var mins = timeAtoms[1];
var amPm = "am";
if ( hours 11) {
if ( hours 12) {
hours = hours - 12;
}
amPm = "pm";
} else if (hours == "0") {
hours = 12;
}
t.value = hours + ":" + mins + " " + amPm;
return(true);
}
var timeAtom = atoms[0];
var amPmAtom = atoms[1];
// Split time into hours, minutes
timeAtoms = timeAtom.split(regexTime);
var hours = timeAtoms[0];
var mins = timeAtoms[1];
// Check hours
if (! regexHour.test(hours)) {
t.value = badFormat;
t.focus();
t.select();
return;
}
// Check minutes
if (! regexMin.test(mins)) {
t.value = badFormat;
t.focus();
t.select();
return;
}
// Check am
if (regexAm.test(amPmAtom) ) {
var amPm = "am";
} else if (regexPm.test(amPmAtom) ) {
var amPm = "pm";
} else {
t.value = badFormat;
t.focus();
t.select();
return;
}
t.value = hours + ":" + mins + " " + amPm;
return(true);
}
See http://kenandrenee.com/timeReformatJs.html for working example.