Software Development

Fix the PHP timezone

Some applications need to know the correct timezone to perform some specific actions and may be a good idea set the date.timezone[1] on PHP configuration to have predictable results in these applications.

If the command below doesn’t give any output, probably the date.timezone is unset.

$ php -r "echo ini_get('date.timezone');"

It is possible to check the date string will be outputted from application with the function date[2] and the current set timezone, using the command below.

$ php -r "echo date('r');"
>>> Fri, 22 Nov 2019 14:28:03 +0000

The +0000 indicates the current timezone is UTC, the PHP default when date.timezone is not set.

After picking a timezone option[3] from PHP documentation, the test to check if that option will give the expected result can be made with the command below, supposing the chosen option is America/Sao_Paulo.

$ php -d date.timezone=America/Sao_Paulo -r "echo date('r');"
>>> Fri, 22 Nov 2019 11:35:38 -0300

The -0300 indicates the America/Sao_Paulo timezone. And to make it persistent, the date.timezone should be set in php.ini. That place of this file may vary from distro to distro.

In Archlinux, all files with the extension .ini dropped in the folder /etc/php/conf.d will be loaded as extensions of php.ini. The command below add the timezone to PHP configuration.

# echo date.timezone=America/Sao_Paulo >> /etc/php/conf.d/my-customs.ini

After that it is possible to run the same commands above to get the date string using the chosen timezone.

$ php -r "echo ini_get('date.timezone');"
>>> America/Sao_Paulo

$ php -r "echo date('r');"
>>> Fri, 22 Nov 2019 11:51:25 -0300