如何通过 Timber 库/WordPress 在 Twig 中输出当地时间?

问题描述

我正在将 Timber Library 与我正在开发的自定义 wordpress 主题一起使用,并且在我的本地时区输出日期的时间非常具有挑战性??我已将 wordpress 设置为 UTC -4:00,这是我的东部 (DST) 时区,但 {{ "Now"|date("F jS \\a\\t g:ia") }} 一直在 7 月 10 日下午 2:26 输出,并且仅在上午 10:22 输出 4 小时! ..所以由于某种原因它没有得到我的 wordpress 设置。我想我可以将其抵消 -4 小时。但我不想在我的代码中这样做,因为我希望用户传递一个我将存储在变量中的值,因此它可以跨不同时区工作!

我对此很陌生,所以需要一些明确的解释:)这就是我想做的 - 要么有时间使用 wordpress 设置,要么传入这样的变量:

// Customer set his own time zone,Now we pass into variable
{{ set timezone = options.local_timezone }}
{{ set timeNow = "Now"|date("F j,S","timezone" }}

{% if condition if post.product.sale_date >= timeNow %}
  {# Then run some code and display product #}
{% else %}
  We are planning to selling this item at post.product.sale_date|date("F j,"timezone" }}
{% endif %}

~感谢您的帮助!

解决方法

较新版本的 Wordpress 更改了处理日期的方式,现在将环境时区设置为始终为 UTC,无论管理中的设置如何。然后它会使用 admin 中的设置在显示天数时应用偏移量,只要您使用 wp_date 函数即可。

在这种情况下,最好依靠 wp_date 而不是与之抗争 - 所以要么将所需的字符串添加到您的上下文中,要么在 twig 中运行该函数。

{{ fn('wp_date','F jS \\a\\t g:ia') }}

这将根据 Wordpress 中的时间设置进行输出。