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); }
Given date in format date, month and year in integer. The task is to find whether the date is possible on not. Valid date should range from 1/1/1800 – 31/12/9999 the dates beyond these are invalid. These dates would not only contains range of year but also all the constraints related to a calendar date.
PHP checkdate() Functionvar_dump(checkdate(12,31,-400));
DateValidator validator = new DateValidatorUsingDateFormat("MM/dd/yyyy"); assertTrue(validator. isValid("02/28/2019")); assertFalse(validator. isValid("02/30/2019"));
You can try this one:
static public function verifyDate($date) { return (DateTime::createFromFormat('m/d/Y', $date) !== false); }
This outputs true/false. You could return DateTime
object directly:
static public function verifyDate($date) { return DateTime::createFromFormat('m/d/Y', $date); }
Then you get back a DateTime
object or false on failure.
UPDATE:
Thanks to Elvis Ciotti who showed that createFromFormat accepts invalid dates like 45/45/2014. More information on that: https://stackoverflow.com/a/10120725/1948627
I've extended the method with a strict check option:
static public function verifyDate($date, $strict = true) { $dateTime = DateTime::createFromFormat('m/d/Y', $date); if ($strict) { $errors = DateTime::getLastErrors(); if (!empty($errors['warning_count'])) { return false; } } return $dateTime !== false; }
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
function was copied from this answer or php.net
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With