30

May

Standard 12-hour time is great for everyone but programmers. I’ve found myself rewriting this little bit of code so often I figured I’d share, to save others the trouble.

12-hour time to 24-hour time:


// Takes a time in g:i a format (e.g. 9:30 am)
function convert($standard) {
   $pieces = split("[: ]", $standard); // Split at colon and space
   $time = array("hours"=>$pieces[0], "minutes"=>$pieces[1], "ampm"=>$pieces[2]); // Rename pieces
   if (stristr($time['ampm'], 'p') && $time['hours'] != 12) $hours = $time['hours'] + 12;  // If it's 1:00 pm or later, add 12 hours
   elseif ($time['hours'] == 12 && stristr($time['ampm'], 'a')) $hours = $time['hours'] - 12; // Otherwise, if it's 12:00 am - 1:00 am, subtract 12 hours
   else $hours = $time['hours']; // Otherwise, don't touch it
   $newtime = $hours . ":" . $time['minutes'] . ":00"; // Format as 22:30:00
   return $newtime;
}


RSS Digg! Delicious StumbleUpon Newsvine Technorati ← Submit me!

3 Responses:

Dennis

Jun 22nd at 3:14 pm

Nice function. What is the example of the $standard value passed in?

Evan

Jun 22nd at 6:09 pm

Sorry, I should have included that right off the bat; the function takes a string in g:i a format (e.g. “9:30 am”).

Gabe

Jul 1st at 11:05 am

I think

elseif ($time['hours'] == 12) $hours = $time['hours'] - 12;

needs an extra condition:

elseif ($time['hours'] == 12 && stristr($time['ampm'], ‘am’))

Since passing 12:30 pm gives me 0:30:00.

Thanks!


Leave a Reply