Gravy
Gravy

Reputation: 12445

Regex. 12 hour time format PHP only allow - 'g:i A'

I am just learning regexes - and have come up with the following PHP regex which I believe works:

/^([1-9]|1[012]):([0-5][0-9]) ((A|P)M)$/

I wish to allow the following string only when validating:

1-12:00-59 AM/PM

To better describe requirements, I need a regex for the following PHP date format

g:i A

Is there a good tool I can use to test this regex? Does anybody have a better regex for me to use?

Upvotes: 1

Views: 886

Answers (1)

Amal Murali
Amal Murali

Reputation: 76646

A regex isn't well suited for parsing dates. Use PHP's DateTime class instead (function by Glavić, from php.net):

function validateDate($date, $format = 'g:i A')
{
    $d = DateTime::createFromFormat($format, $date);
    return $d && $d->format($format) == $date;
}

Upvotes: 3

Related Questions