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.

.env

APP_TIMEZONE=America/New_York

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

config/services.yaml

parameters:
    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.

src/Kernel.php

<?php

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
    {
        parent::boot();
        date_default_timezone_set($this->getContainer()->getParameter('timezone'));
    }
}

The following code can be used for testing:

src/Controller/TestController.php

<?php

namespace App\Controller;

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

class TestController
{
    #[Route('/')]
    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

    parent::boot();
    date_default_timezone_set($this->getContainer()->getParameter('timezone'));

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

    • 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.