How do I output the local time in Twig via Timber library/WordPress?

Viewed 165

I'm using the Timber Library with my custom Wordpress theme I am Developing and having an exceedingly challenging time outputting the date in my local time zone?? I have WordPress set to UTC -4:00 which is my Eastern (DST) timezone but {{ "now"|date("F jS \\a\\t g:ia") }} keeps outputting July 10th at 2:26pm and its only 10:22am which is 4hrs off! ..so it isn't getting my WordPress setting for some reason. I imagine I could offset this by -4 hrs. but I don't want to do this in my code as I would like the user to pass a value that I will store in a variable, so it works across various time zone!

I am pretty new at this so need some clear explanation :) Here is what I would like to do - either have the time be right with WordPress settings or pass in a variable like this:

// 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, S", "timezone" }}
{% endif %}

~ Thanks for any help!

1 Answers

A fairly recent version of Wordpress made a change to the way dates are handled, and now sets the environments time zone to always be UTC, regardless of settings in the Admin. It then uses the settings in admin to apply the offset when displaying days, as long as you use wp_date functions.

In this scenario, your better off relying on wp_date instead of fighting it - so either add the desired string to your context or run the function in twig.

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

This will output based on the time settings in Wordpress.

Related