0

When I use the date() function in a Twig template, it returns universal time, as opposed to the date filter which returns the correct time with the proper timezone applied.

I am using

date_default_timezone_set('America/Los_Angeles');

in my theme's functions.php file for some other non-related functionality, which does appear to directly screw with these dates (when the line of code is removed, the date seems to render correctly). I could use the date_modify filter, but I'm working with a date between now and the daylight savings time switchover, so it unnecessarily affects what I'm trying to accomplish here.

After reading the Twig docs on the date() function, I thought the following in my functions.php file would work, but it doesn't appear to have any affect:

function add_to_twig( $twig ) {
    $twig->getExtension(\Twig\Extension\CoreExtension::class)->setTimezone('America/Los_Angeles');
    return $twig;
}

So what's the correct way to tell Timber/Twig the timezone to use?

Talk Nerdy To Me
  • 626
  • 5
  • 21
  • What you mean by "it doesn't have any effect". How are you verifying this? – DarkBee Oct 25 '19 at 06:41
  • @DarkBee With or without the `$twig->getExtension` line, `{{ date('now') }}` outputs the same time. – Talk Nerdy To Me Oct 25 '19 at 17:20
  • Have a look at [this](https://stackoverflow.com/a/8668342/446594) – DarkBee Oct 28 '19 at 06:41
  • @DarkBee Thank you, but that's a PHP answer and I could essentially create and manipulate my date objects before the template, but I'm really looking to solve the Twig issue. I have opened an issue ticket on github: https://github.com/timber/timber/issues/2104 – Talk Nerdy To Me Oct 28 '19 at 16:43

1 Answers1

0

First is necessary to add the Extension:

$twig->addExtension(new Twig\Extension\CoreExtension );

After that, you are free to use the same code you tried, available in the twig documentation.

So, the best option for sure would be use the timezone configured in WordPress.

The full code is:

public function add_to_twig($twig)
{
    /*HERE YOUR OTHER STUFF*/

    //Add the CoreExtension
    $twig->addExtension(new Twig\Extension\CoreExtension );

    //Get the timezone from Wordpress and use the extension to set the timezone
    $timezone = get_option('timezone_string');
    $twig->getExtension(\Twig\Extension\CoreExtension::class)->setTimezone($timezone);

    return $twig;
}
Alvin
  • 762
  • 4
  • 14