PHP complains date.timezone is not set

Sometimes, PHP will kick up a fuss complaining about date.timezone not being set. We found this on the Symfony framework and were able to replicate it on standalone scripts.

[Exception]
DateTime::__construct(): It is not safe to rely on the system's timezone settings.
You are required to use the date.timezone setting or the date_default_timezone_set()
function. In case you used any of those methods and you are still getting this
warning, you most likely misspelled the timezone identifier.
We selected 'Europe/Berlin' for 'CEST/2.0/DST' instead

Normally, you would fix this by editing your php.ini file and adding a declaration there.

date.timezone = "Europe/Berlin"

But we had already done this and it still wasn’t working! After some further investigation, it seemed that PHP simply couldn’t access the value.

echo(ini_get("date.timezone"));

This doesn’t make any sense, and we never got to the bottom of what was going on, but there are two ways around the problem. Firstly, you could modify your PHP script so that it makes a call to set the system timezone.

date_default_timezone_set("Europe/Berlin");

However, this involves having to modify your code, which is bad as you don’t want to have to set the timezone manually, especially in a piece of code which could be deployed to servers in different timezones.

A better approach is to set it in the vhosts directive in Apache.

php_value "date.timezone" "Europe/Berlin"

This isn’t the cleanest solution but allowed us to solve an otherwise unexplainable error.