DEV Community

Yongyao Yan
Yongyao Yan

Posted on • Originally published at codebilby.com

Render a DateTime Object in Twig

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);

$twig->getExtension(\Twig\Extension\CoreExtension::class)->setTimezone('Australia/Melbourne');

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

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

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") }}
Enter fullscreen mode Exit fullscreen mode

The output will be:

05 Jul 2010 06:00
Enter fullscreen mode Exit fullscreen mode

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

{{ "now"|date("d M Y H:i") }}
Enter fullscreen mode Exit fullscreen mode

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.

<p>
   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") }}
</p>
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

Thanks for reading!
To find more programming tutorials, please visit: CodeBilby.com

Top comments (0)