Faced the following error in a function that returns the current time with microseconds:
Fatal error: Call to a member function setTimeZone() on boolean
The code this function is:
public static function getCurrentTime() {
$microtime = microtime(true);
$time = DateTime::createFromFormat('U.u', (int) $microtime != $microtime ? $microtime : $microtime + 0.001);
$time->setTimeZone(new DateTimeZone(date_default_timezone_get()));
return $time->format('Y-m-d H:i:s.u');
}
This error occurs with a small proportion of users (<1%). I know that setTimeZone()
can return false
if a problem occurs, but how can I avoid this problem in my code? Why does setTimeZone()
return false
?
I am using PHP Version 7.0.9
.