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

  2. Avatar
    Steve Reply

    Hello and thank you for the tutorial.
    I get the error "You have requested a non-existent parameter "timezone"." when clearing the prod cache via the console. Do you have an idea?

    • Avatar
      lindevs Reply

      Hi,
      Ensure that you have defined the timezone parameter in the config/services.yaml file. Here are some tips to troubleshoot the issue:
      * Test in the dev environment to see if the problem persists.
      * Try using a different parameter to verify that your Symfony project is correctly reading the config/services.yaml file.

Leave a Comment

Cancel reply

Your email address will not be published.