Strange (caching?) issue concerning date/time

MathijsDelva
Tourist
11 0 1

Hi!

 

My goal is to schedule a promotion based upon three datetimes:

 

1. now

2. promotion_start_date

3. promotion_end_date

 

If 'now' is between promotion_start_date & promotion_end_date, the promotion must be shown. promotion_end_date & promotion_end_date values come from metafields. I have this code:

 

 

 

{% assign seconds = 5 | times: 24 | times: 60 %}
{% assign current_date = 'now' | date: "%d/%m/%Y, %H:%M:%S" %}
{% assign promotion_start_date = shop.metafields.promotion.promotion_start | date: "%s" | minus: seconds | date: "%d/%m/%Y, %H:%M:%S" %}
{% assign promotion_end_date = shop.metafields.promotion.promotion_end | date: "%s" | minus: seconds | date: "%d/%m/%Y, %H:%M:%S" %}
{% if current_date > promotion_start_date and current_date < promotion_end_date %}
    {% capture promotion_is_live %}{{shop.metafields.promotion.is_active}}{% endcapture %}
{% endif %}

 

 

 

I've included this inside a snippet and added it to theme.liquid's <head>. There, this works perfectly. I continuously update the metafields values to toggle the promotion on and off, and upon refresh, i get a nice "{{ current_date }}" printed (which is perfectly live and not cached) and a conditional output as per test:

 

 

 

{{ current_date }}
{% if promotion_is_live %}
promotion_is_live
{% else %}
promotion_is_not_live
{% endif %}

 

 

Now the issue i have is the following:

 

When using the "{% if promotion_is_live %}" conditional in my templates, it doesn't work. As per the same test, i also added the output (promotion_is_live & promotion_is_not_live) as in the <head>. So now i see "promotion_is_live" in the <head> but "promotion_is_not_live" in the template ..

How is this possible? 

 

FYI: shop.metafields.promotion.is_active outputs a boolean.

 

Reply 1 (1)
Jason
Shopify Expert
10869 190 2169

You should always assume that now will return the time that the view was cached, not the current now.

 

Updating a metafield would clear the cache so when you view the page again you would see a freshly cached view with new time. On a second viewing (and assuming the metafield hasn't been changed) you'd still see that initial now time.

This is the intended outcome so you may need to tweak your approach.

 

 

★ I jump on these forums in my free time to help and share some insights. Not looking to be hired, and not looking for work. http://freakdesign.com.au ★