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
.
APP_TIMEZONE=America/New_York
Define a new parameter timezone
in the services.yaml
file.
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.
<?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:
<?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
Kernel
class haspreboot
method. When Symfony application is used via web,preboot
method is executed beforeboot
method. Thepreboot
method initializes container. However, error occurs using Symfony console command becauseboot
method 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
timezone
parameter in theconfig/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