Saturday, April 4, 2009

PHP: Using REGEX Convert standard time into AM-PM

There are many ways in php to convert the provided 24 hours time format hh:mm:ss into hh:mm AM/PM format. I'm giving an example about this conversion using Regular Experssion. Using preg_replace() of your PHP script, just convert the time under /e modifier of your regular expression. Below is the one line code.

$time = preg_replace('/(\d+):(\d+):\d+/e', '($1<12)?"$1:$2 AM":$1-12 . ":$2 PM"', $time);

Here, first I have taken the hour and minute portion from the time using regular expression. It will be at $1 and $2 variables. Then inside the replacement section, I have checked whether the hour is less than 12 or not ($1<12), using this I have placed the AM or PM after the hh:mm, and also I have deducted 12 from hour section if it is more than 12.

This regular expression may comes hard to understand, but this is only for REGEX lovers who wants to convert the 24 hours time format into 12 hrs AM-PM time format. Cheers!!!


Anonymous said...

This is great. Could you explain what the 'replace' code is doing? I am trying to go the other direction, ie from 630AM to 06:30.

Thanks for posting this explanation.

Anonymous said...

12:00:00 converts to 0:00 PM instead of 12:00 AM :(

Get function name programaticaly - Python

This little piece of code will help you to get the function name programatically. This is very helpful when you are implementing the debug...