14

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
  • 27,280
  • 43
  • 127
  • 177
  • 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

15

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
  • 922
  • 4
  • 10
  • This is better than regex which I was about to suggest, thanks. – francisco.preller Apr 07 '13 at 04:07
  • This doesn't work for dates missing a space between day and hour. ie. 2021-10-0603:58:00. PHP interprets this well but MySQL does not. MySQL converts it to 2021-10-07 00:00:00. – Rooster242 Oct 11 '21 at 16:57
  • This doesn't work for strings like '0001-11-11 00:00:00', this method approves them as appropriate, while mysql will give you an error here. – klm123 Apr 23 '23 at 13:46
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
  • 335
  • 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