Convert a 24-hour time to a 12-hour time

Converts 24-hour time to 12-hour time with an AM or PM designation.
JavaScript


function format24Time(time24hour) {
	if (time24hour.toString()=='0000') { return "12:00am" }
	// converts a 24-hour time (hhmm) to 12-hour time (hh:mm a/p)
	if (time24hour.toString().length === 3) {
		// in case leading zero isn't there for the hour
		time24hour = '0' + time24hour;
	}
	var hour = parseInt(time24hour.toString().substring(0,2), 10);
	var minute = time24hour.toString().substring(2,4);
	var meridian = 'am';
	if(hour > 12) {
		hour -= 12;
		meridian = 'pm';
	}
	var returnTime = hour.toString();
	returnTime += ':' + minute;
	returnTime += meridian;	
	return returnTime;
}

Examples:

HHMM to HH:MM AM/PM
0200 would be converted to 2:00am
1630 would be converted to 4:30pm

Written by http://www.sitekickr.com/snippets/javascript/convert-hour-time-hour-time

Posted by fbrefere001 on Wednesday August 27, 2014