How to check string's date format in PHP?

kaspernov picture kaspernov · Aug 17, 2011 · Viewed 29.2k times · Source

I would like to check if the string has this time format:

Y-m-d H:i:s

and if not than do some code e.g.

if here will be condition do { this }
else do { this }

How to do this condition in PHP?

Answer

Shad picture Shad · Aug 17, 2011

preg_match is what you are looking for, specifically:

if(preg_match('/\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}/',$date)){
   //dothis
}else{
   //dothat
}

if you REALLY ONLY want properly formatted date, then

/\d{4}-[01]\d-[0-3]\d [0-2]\d:[0-5]\d:[0-5]\d/