Function to check if a string is a date

Justin picture Justin · Jun 14, 2012 · Viewed 112.2k times · Source

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.

Answer

Joey picture Joey · Jun 14, 2012

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
}