Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fast way in PHP to check if a value is in MySQL datetime format?

Tags:

string

php

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

like image 528
Kirk Ouimet Avatar asked Apr 07 '13 03:04

Kirk Ouimet


People also ask

How do you check if a value is a date in PHP?

Example: $x = {1,2,3,"4","11/12/2009","22/12/2000",true,false}; foreach($x as $value) { if(is_bool($value)) if(is_string($value)) if(is_numeric($value)) if(is_date($value)) ? ... }

How does MySQL compare time in PHP?

Just comparing two timestamps would suffice: $t1 = strtotime($time); $t2 = strtotime($Max_Time); if($t1 > $t2) { .. } Save this answer.

What format displays datetime values MySQL?

MySQL retrieves and displays DATETIME values in ' YYYY-MM-DD hh:mm:ss ' format. The supported range is '1000-01-01 00:00:00' to '9999-12-31 23:59:59' . The TIMESTAMP data type is used for values that contain both date and time parts.

How can I get current date and time in MySQL and PHP?

The CURRENT_TIMESTAMP function in the MySQL database returns the current date and time (i.e. the time for the machine running that instance of MySQL). It is given as a value in the 'YYYY-MM-DD hh:mm:ss' format.


2 Answers

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

like image 85
epicdev Avatar answered Oct 21 '22 16:10

epicdev


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

like image 32
Mohammed Farag Avatar answered Oct 21 '22 15:10

Mohammed Farag