Search code examples
phpdatedatetimetimezone

Will getTimezone() EVER return false when invoked on a PHP DateTime or DateTimeImmutable object?


In the docs it says that the function returns a DateTimeZone object on success or false on failure. My question is, in which cases will this result in a failure?

In my experience, it is never failing and it always returns a DateTimeZone object.


Solution

  • It can return false prior to PHP v8, when the typehint was added for the DateTimeInterface $object parameter:

    var_dump(date_timezone_get(0));
    

    In PHP >= 8.0:

    Fatal error: Uncaught TypeError: date_timezone_get():
      Argument #1 ($object) must be of type DateTimeInterface, int given
    

    In PHP < 8.0:

    bool(false)