Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check string's date format in PHP?

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?

like image 375
kaspernov Avatar asked Aug 17 '11 21:08

kaspernov


People also ask

How can check string is date format or not in PHP?

In order to check if a string is a date or not, you can use the strtotime() method. Note: The strtotime() method functions by parsing an English datetime string into a UNIX timestamp.

How do I know if a date is in format?

Checking whether the date passed to query is the date of the given format or not: SQL has IsDate() function which is used to check the passed value is date or not of specified format, it returns 1(true) when the specified value is date otherwise it return 0(false).


1 Answers

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/
like image 127
Shad Avatar answered Sep 27 '22 22:09

Shad