7
I have seen two different ways to check whether a date is valid.
In a "modern" way, with DateTime
:
$date="2014-02-04";
$dt = DateTime::createFromFormat("Y-m-d", $date);
return $dt !== false && !array_sum($dt->getLastErrors());
And using a regular expression:
$date="2014-02-04";
// regex bem simples, apenas para demonstrar a situação.
return (preg_match("/^[0-9]{4}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])$/",$date));
I didn’t find much comparative information about these methods. I know that the DateTime
is more modern, but this is enough to consider it more recommendable? What are the advantages and disadvantages of each method?
I recommend the use of the http://www.php.net/manual/en/class.datetime.phpclass, as well as being specialized in dates Regular expressions should be used in the last case, as it is quite expensive both to work with them and to the server. May in some cases cause slowness.
– Iago Leão