Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Verify valid date using PHP's DateTime class

Tags:

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); } 
like image 684
user1032531 Avatar asked Jan 24 '13 15:01

user1032531


People also ask

How do you check if a date is valid?

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.

How do you check a date is valid in PHP?

PHP checkdate() Functionvar_dump(checkdate(12,31,-400));

How do you check if a date is a valid date in Java?

DateValidator validator = new DateValidatorUsingDateFormat("MM/dd/yyyy"); assertTrue(validator. isValid("02/28/2019")); assertFalse(validator. isValid("02/30/2019"));


2 Answers

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; } 
like image 122
bitWorking Avatar answered Sep 19 '22 15:09

bitWorking


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

like image 33
Faiyaz Alam Avatar answered Sep 18 '22 15:09

Faiyaz Alam