Yan's Blog

Yan's Blog

Render a DateTime Object in Twig

Render a DateTime Object in Twig

Subscribe to my newsletter and never miss my upcoming articles

The date filter

In Twig, the date filter uses the same DateTime format of PHP to render DateTime instances in server-side.

require_once './vendor/autoload.php';

$loader = new \Twig\Loader\FilesystemLoader('./themes');

$twig = new \Twig\Environment($loader);


$dt = new DateTime("2010-07-05 06:00:00", new DateTimeZone("Australia/Melbourne"));

echo $twig->render('render-a-datetime.twig', array("myDateTime" => $dt));

In the above PHP code snippet, the function setTimezone is used to set the default timezone globally in Twig. The new DateTime instance $dt is created with the timezone of Australia/Melbourne. After that, it is passed to the template file render-a-datetime.twig. In the template file, we can render the DateTime variable myDateTime like this:

{{ myDateTime|date("d M Y H:i") }}

The output will be:

05 Jul 2010 06:00

If want to show the current date in Twig, we can use the word now.

{{ "now"|date("d M Y H:i") }}

The date filter with a timezone

We can override the default timezone in the date filter with a given timezone string. For the details of the supported timezones, you can refer to List of Supported Timezones. For example, you can display the current date instance for different cities.

   New York: {{ "now"|date("d M Y H:i", "America/New_York") }} <br>
   Paris: {{ "now"|date("d M Y H:i", "Europe/Paris") }} <br>
   Hong Kong: {{ "now"|date("d M Y H:i", "Asia/Hong_Kong") }} <br>
   Melbourne: {{ "now"|date("d M Y H:i", "Australia/Melbourne") }}

The above code will output:

New York: 20 Oct 2020 20:30
Paris: 21 Oct 2020 02:30
Hong Kong: 21 Oct 2020 08:30
Melbourne: 21 Oct 2020 11:30
Share this