jeffery_the_wind jeffery_the_wind - 3 years ago 188
PHP Question

PHP verify correct time format in $value

I have an online form that has a few fields with time data. I store this data into the MySQL data base into a

field, which needs a format
. If the user inputs the time in this format correctly, then i want to accept the data. I also want to allow users to input the time in standard US time, like
9:30 am
11:25 pm
10:27 am

Basically I want to test if the time is in the proper database format first (
), then if it is not, test if it is in the second accepted format (
hh:mm am/pm
), and if it is, then I will use the PHP function
to convert it into the database time format. If it is in neither of these formats, then we display an error message and die.

Does anyone know how to test if the value of a variable matches one of these time formats?

Pseudo PHP code of what I want to do:

$value = //some time;
if (is_database_time($value)){
// good no problem
}else if (is_usa_time($value)){
$value = strtotime($value);
die("error incorrect time format, try again.");

** EDIT **

Thanks everyone for the help. I used some of the info here to make a function that works perfectly:

function filter_time($key,$value){
// this section handles the storage of time data
if (preg_match('/^(0?\d|1\d|2[0-3]):[0-5]\d:[0-5]\d$/', $value)){
//do nothing
}else if (preg_match('/^(0?\d|1[0-2]):[0-5]\d\s(am|pm)$/i', $value)){
$value = date( 'H:i:s', strtotime($value));
display_error('incorrect time format in '.$key.' field.');
return $value;

Answer Source

function verify_time_format()

function verify_time_format ($value) {

  $pattern1 = '/^(0?\d|1\d|2[0-3]):[0-5]\d:[0-5]\d$/';
  $pattern2 = '/^(0?\d|1[0-2]):[0-5]\d\s(am|pm)$/i';
  return preg_match ($pattern1, $value) || preg_match ($pattern2, $value);


Returns TRUE for following values:

15:23 AM
15:23 am
09:41 pm
9:41 PM


function filter_time ($key, $value) {

  $p1 = '/^(0?\d|1\d|2[0-3]):[0-5]\d:[0-5]\d$/';
  $p2 = '/^(0?\d|1[0-2]):[0-5]\d\s(am|pm)$/i';

  if (preg_match ($p1, $value) || preg_match ($p2, $value))
    $res = date ('H:i:s', strtotime ($value));

    display_error ("incorrect time format in {$key} field.");

  return $res;

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download