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

Converts 24-hour time to 12-hour time with an AM or PM designation.
time24hourTo12hour = function(time24hour) {
	// 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;
}
Posted by
Snippet Viewed 2490 times.

Share your JavaScript code snippets:

  • Get some recognition & a link back to your site.
  • Create your own code library.
  • Help your fellow developers, as they have helped you.

 

Submit | Browse

Most Recent javascript snippets

Most Viewed