How to check if the date within the DateTime is invalid?

2

Working in an application with PHP 5.5 + Symfony 2 + Doctrine.

In one of the tables in this application there is a updated_at field that is initially NULL . However, when I give getUpdatedAt() to this entity, I get an object of type \DateTime , and its content is as follows:

object(DateTime)#1064 (3) {
  ["date"]=>
  string(27) "-0001-11-30 00:00:00.000000"
  ["timezone_type"]=>
  int(3)
  ["timezone"]=>
  string(17) "America/Sao_Paulo"
}

How to test, without too much hassle, if this object was generated from a null date?

    
asked by anonymous 02.02.2015 / 17:49

2 answers

0

I found the right way.

If I try to create a \ DateTime object from an invalid date:

$data = new \DateTime('00-00-00 00:00:00');

Just check for any errors that the \DateTime constructor had to read the argument using the getLastErrors method:

var_dump($data->getLastErrors());

Result:

array(4) {
  ["warning_count"]=>
  int(1)
  ["warnings"]=>
  array(1) {
    [18]=>
    string(27) "The parsed date was invalid"
  }
  ["error_count"]=>
  int(0)
  ["errors"]=>
  array(0) {
  }
}
    
10.02.2015 / 18:45
0

I've had this same problem and used a very simple solution to check.

When DateTime is created with this null date, the format method returns -1 for the year. If it returns any value above 0, it means the date is valid.

if((int)$date->format('y') > 0) {
 // válida!
} else {
 // inválida!
}
    
02.02.2015 / 18:13