Return to Snippet

Revision: 59663
at September 23, 2012 10:29 by kosinix


Initial Code
<?php
function to_24_hour($hours,$minutes,$seconds,$meridiem){
	$hours = sprintf('%02d',(int) $hours);
	$minutes = sprintf('%02d',(int) $minutes);
	$seconds = sprintf('%02d',(int) $seconds);
	$meridiem = (strtolower($meridiem)=='am') ? 'am' : 'pm';
	return date('H:i:s', strtotime("{$hours}:{$minutes}:{$seconds} {$meridiem}"));
}

echo to_24_hour( 1, 2, 3, 'pm' ); // Returns 13:02:03
echo to_24_hour( '02', '30', '00', 'pm' ); // Returns 14:30:00
?>

Initial URL

                                

Initial Description
Convert 12-hour time format with hour, minutes, seconds, and meridiem into 24-hour  format. Performs data correction to make sure hours, minutes and seconds have leading zeros if needed.

The trick here is to use strtotime() where we pass the time string in this format: "hh:mm:ss meridiem" 
Example: "02:30:00 pm"

Initial Title
PHP Function to Convert 12 Hour Time to 24 Hour Format

Initial Tags
function, convert

Initial Language
PHP