How to check if the date inside Datetime is invalid?

Asked

Viewed 819 times

2

Work on an application with PHP 5.5 + Symfony 2 + Doctrine.

In one of the tables of this application there is a field updated_at which is initially NULL. However, when I give one getUpdatedAt() in this entity, I am returned an object of the type \DateTime, and whose 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 many tricks, whether this object was generated from a null date?

  • The problem is that it has already been created as a date! If you had one DateTime::createFromFormat internally would give to make a $date instanceof DateTime to verify!

  • Can’t you do a check of the pure attribute that comes from the bank to then check? something like if ($data->updated_at !== NULL) { $data->getUpdatedAt() } ?

  • @Wallacemaxters is a possibility, I can try to verify within the entity itself. But I didn’t want to have to do this with all classes that have a date field that can be null.

  • Makes a Trait! You are using PHP 5.5. You can do a horizontal inheritance, where all the classes that implement this Trait will have this method with the checks. I already made it in the Laravel

  • that helps? [link]http://stackoverflow.com/questions/14504913/verify-valid-date-using-phps-datetime-class[/link]

  • I found a way, look at my answer. :)

Show 1 more comment

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');

It is sufficient to verify any errors that the manufacturer of \DateTime had to read the argument using the method getLastErrors:

var_dump($data->getLastErrors());

Upshot:

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

0

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

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

if((int)$date->format('y') > 0) {
 // válida!
} else {
 // inválida!
}
  • I found a native way to validate the date, see the answer I posted.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.