13

Does anyone know if there is a built in or quick function to check if a string is a MySQL datetime format? Here is an example:

2038-01-19 03:14:07

http://dev.mysql.com/doc/refman/5.0/en/datetime.html

Kirk Ouimet
  • 25,594
  • 43
  • 117
  • 167
  • Possible duplicate of http://stackoverflow.com/questions/2215354/php-date-format-when-inserting-into-datetime-in-mysql See php [`date()`](http://php.net/manual/en/function.date.php) documentation. Example: `date("Y-m-d H:i:s")` – Aiias Apr 07 '13 at 03:54

2 Answers2

14

You can try DateTime::createFromFormat('Y-m-d H:i:s', '2038-01-19 03:14:07') and see if it returns false. http://www.php.net/manual/en/datetime.createfromformat.php

epicdev
  • 912
  • 4
  • 10
12

I loved the answer by epicdev, however, the class seems to only validate the format, a date like 2015-18-39 is still valid for it and is converted to 2016-07-09 instead of rejecting the invalid day/month A slight change to it is to double check that the date parsed is still the same as the date entered.

function proposed by glavic at gmail dot com on php.net documentation

function validateDate($date, $format = 'Y-m-d H:i:s')
{
    $d = DateTime::createFromFormat($format, $date);
    return $d && $d->format($format) == $date;
}

function was copied from this answer or php.net

Community
  • 1
  • 1
Mohammed Farag
  • 325
  • 2
  • 9
  • This worked for me. Not sure if it is the same with **OP** @102635 – Abel Callejo Sep 19 '17 at 08:34
  • For the same reason at I stated in epicdev's answer this doesn't work for dates missing the space between the day and hour. I haven't tested anything else. – Rooster242 Oct 11 '21 at 16:58
  • @Rooster242 Can you put an example? I don't understand the issue. I tested this function with '2021-10-0603:58:00' and I got false as expected – Mohammed Farag Oct 12 '21 at 20:53