How can I set timezone in symfony 3?

Argoitz picture Argoitz · May 11, 2018 · Viewed 13.7k times · Source

I have a symfony 3 application deployed in Ubuntu 14.04 server.

When I execute "date" in the command window, the server response me "Fri May 11 10:02:30 CEST 2018" but when I dump a datetime in twig as "{{ dump("now"|date) }}", the response is "May 11, 2018 04:04".

If I put in the header of the controller function (route), "date_default_timezone_set("Europe/Madrid");" it works fine, but I don't want to copy this line in all functions of all controllers.

Then, I want to know where can I set the Timezone as configuration of Symfony or where can I set this PHP command (date_default_timezone_set("Europe/Madrid")) globally for all the controllers.

Thank you

[EDIT]

One solution may be put this code in the header of the controller, but I want to set it ones, no in all controllers, services, etc...:

public function __construct(){
    date_default_timezone_set("Europe/Madrid");
}

Answer

lxg picture lxg · Oct 5, 2018

If you can’t set it in php.ini, or you want to be sure the value is consistent independently of the target environment, the easiest way is to set it in your AppBundle:

class AppBundle extends Bundle
{
    public function boot()
    {
        parent::boot();
        date_default_timezone_set("Europe/Madrid");
    }
}

Alternatively, if you don’t have an AppBundle (or any other own bundle), you could add it to the AppKernel::registerBundles() method, right before the bundles are loaded.