Set Default Date Format and Time Zone for Twig Template in Symfony 6

Set Default Date Format and Time Zone for Twig Template in Symfony 6

Symfony framework applies the default date format and time zone when date filter is used in the Twig template. The default date format and time zone can be overridden by providing arguments for date filter. It is not good solution when custom date format and time zone should be applied for all Twig templates.

This tutorial shows how to set default date format and time zone for Twig template in Symfony 6 application.

The format and timezone options can be used under the twig.date key to define the default date formatting and time zone for all Twig templates:

config/packages/twig.yaml

twig:
    date:
        format: 'M d, Y g:i A'
        timezone: 'America/New_York'

In order to test create the controller and template which uses date filter:

templates/test/index.html.twig

{{ 'now'|date }}

src/Controller/TestController.php

<?php

namespace App\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;

class TestController extends AbstractController
{
    #[Route('/')]
    public function index(): Response
    {
        return $this->render('test/index.html.twig');
    }
}

Leave a Comment

Cancel reply

Your email address will not be published.