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
Nice tip, but you can invert the lines
otherwise, you receive the following error:
`Cannot retrieve the container from a non-booted kernel.`
Thanks
Kernelclass hasprebootmethod. When Symfony application is used via web,prebootmethod is executed beforebootmethod. Theprebootmethod initializes container. However, error occurs using Symfony console command becausebootmethod is executed first and container is not initialized. I updated the code in the tutorial. Thanks, JellyBellyDev. Very well observed.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?
Hi,
Ensure that you have defined the
timezoneparameter in theconfig/services.yamlfile. Here are some tips to troubleshoot the issue:* Test in the
devenvironment to see if the problem persists.* Try using a different parameter to verify that your Symfony project is correctly reading the
config/services.yamlfile.Leave a Comment
Cancel reply