Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function to check if a string is a date

I am trying to write a function to determine if a string is a date/time using PHP. Basically a valid date/time would look like:

 2012-06-14 01:46:28 

Obviously though its completely dynamic any of the values can change, but it should always be in form of XXXX-XX-XX XX:XX:XX, how can I write a regular expression to check for this pattern and return true if matched.

like image 268
Justin Avatar asked Jun 14 '12 08:06

Justin


2 Answers

If that's your whole string, then just try parsing it:

if (DateTime::createFromFormat('Y-m-d H:i:s', $myString) !== false) {   // it's a date } 
like image 172
Joey Avatar answered Sep 21 '22 10:09

Joey


Easiest way to check if a string is a date:

if(strtotime($date_string)){     // it's in date format } 
like image 26
Yogesh Mistry Avatar answered Sep 21 '22 10:09

Yogesh Mistry