Skip to content

Instantly share code, notes, and snippets.

@kosinix
Created March 9, 2013 09:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kosinix/5123613 to your computer and use it in GitHub Desktop.
Save kosinix/5123613 to your computer and use it in GitHub Desktop.
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"
<?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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment