'Verify valid date using PHP's DateTime class
Below is how I previously verified dates. I also had my own functions to convert date formats, however, now am using PHP's DateTime class so no longer need them. How should I best verify a valid date using DataTime? Please also let me know whether you think I should be using DataTime in the first place. Thanks
PS. I am using Object oriented style, and not Procedural style.
static public function verifyDate($date)
{
//Given m/d/Y and returns date if valid, else NULL.
$d=explode('/',$date);
return ((isset($d[0])&&isset($d[1])&&isset($d[2]))?(checkdate($d[0],$d[1],$d[2])?$date:NULL):NULL);
}
Solution 1:[1]
With DateTime you can make the shortest date&time validator for all formats.
function validateDate($date, $format = 'Y-m-d H:i:s')
{
$d = DateTime::createFromFormat($format, $date);
return $d && $d->format($format) == $date;
}
var_dump(validateDate('2012-02-28 12:12:12')); # true
var_dump(validateDate('2012-02-30 12:12:12')); # false
Solution 2:[2]
You could check this resource: http://php.net/manual/en/datetime.getlasterrors.php
The PHP codes states:
try {
$date = new DateTime('asdfasdf');
} catch (Exception $e) {
print_r(DateTime::getLastErrors());
// or
echo $e->getMessage();
}
Solution 3:[3]
Try this:
function is_valid_date($date,$format='dmY')
{
$f = DateTime::createFromFormat($format, $date);
$valid = DateTime::getLastErrors();
return ($valid['warning_count']==0 and $valid['error_count']==0);
}
Solution 4:[4]
$date[] = '20/11/2569';
$date[] = 'lksdjflskdj';
$date[] = '11/21/1973 10:20:30';
$date[] = '21/11/1973 10:20:30';
$date[] = " ' or uid like '%admin%";
foreach($date as $dt)echo date('Y-m-d H:i:s', strtotime($dt))."\n";
Output
1970-01-01 05:30:00
1970-01-01 05:30:00
1970-01-01 05:30:00
1973-11-21 10:20:30
1970-01-01 05:30:00
1970-01-01 05:30:00
Solution 5:[5]
I needed to allow user input in (n) different, known, formats...including microtime. Here is an example with 3.
function validateDate($date)
{
$formats = ['Y-m-d','Y-m-d H:i:s','Y-m-d H:i:s.u'];
foreach($formats as $format) {
$d = DateTime::createFromFormat($format, $date);
if ($d && $d->format($format) == $date) return true;
}
return false;
}
Solution 6:[6]
With the following an empty string like '' or 0 or '0000-00-00 00:00:00' is false
$valid = strtotime($date) > 0;
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Glavić |
| Solution 2 | shadyyx |
| Solution 3 | AstroCB |
| Solution 4 | bluepinto |
| Solution 5 | julius patta |
| Solution 6 | M-Phil |
