Set Default Time Zone in Symfony 7

Set Default Time Zone in Symfony 7

Sometimes, we may need to specify the default time zone in application, which will be used by date and time functions. This tutorial provides example how to set default time zone in Symfony 7 application.

In the .env file, add new environment variable APP_TIMEZONE.



Define a new parameter timezone in the services.yaml file.


    timezone: '%env(APP_TIMEZONE)%'

In the Kernel class override boot method and retrieve the timezone parameter from container. Set the default time zone used by date and time functions with date_default_timezone_set function.



namespace App;

use Symfony\Bundle\FrameworkBundle\Kernel\MicroKernelTrait;
use Symfony\Component\HttpKernel\Kernel as BaseKernel;

class Kernel extends BaseKernel
    use MicroKernelTrait;

    public function boot(): void

The following code can be used for testing:



namespace App\Controller;

use DateTime;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;

class TestController
    public function index(): Response
        $now = new DateTime();

        return new Response($now->getTimezone()->getName()); // Output: America/New_York

The 2 Comments Found

  1. Avatar
    JellyBellyDev Reply

    Nice tip, but you can invert the lines


    otherwise, you receive the following error:
    `Cannot retrieve the container from a non-booted kernel.`

    • Avatar
      lindevs Reply

      Kernel class has preboot method. When Symfony application is used via web, preboot method is executed before boot method. The preboot method initializes container. However, error occurs using Symfony console command because boot method is executed first and container is not initialized. I updated the code in the tutorial. Thanks, JellyBellyDev. Very well observed.

Leave a Comment

Cancel reply

Your email address will not be published.