1function get24hTime(str){
2 str = String(str).toLowerCase().replace(/\s/g, '');
3 var has_am = str.indexOf('am') >= 0;
4 var has_pm = str.indexOf('pm') >= 0;
5 // first strip off the am/pm, leave it either hour or hour:minute
6 str = str.replace('am', '').replace('pm', '');
7 // if hour, convert to hour:00
8 if (str.indexOf(':') < 0) str = str + ':00';
9 // now it's hour:minute
10 // we add am/pm back if striped out before
11 if (has_am) str += ' am';
12 if (has_pm) str += ' pm';
13 // now its either hour:minute, or hour:minute am/pm
14 // put it in a date object, it will convert to 24 hours format for us
15 var d = new Date("1/1/2011 " + str);
16 // make hours and minutes double digits
17 var doubleDigits = function(n){
18 return (parseInt(n) < 10) ? "0" + n : String(n);
19 };
20 return doubleDigits(d.getHours()) + ':' + doubleDigits(d.getMinutes());
21}
22
23console.log(get24hTime('6')); // 06:00
24console.log(get24hTime('6am')); // 06:00
25console.log(get24hTime('6pm')); // 18:00
26console.log(get24hTime('6:11pm')); // 18:11
27console.log(get24hTime('6:11')); // 06:11
28console.log(get24hTime('18')); // 18:00
29console.log(get24hTime('18:11')); // 18:11
30