14

I'm attempting to create a "Pre-Order" Like mechanic where certain elements of my Shopify Liquid Template only show if the current date is more or less than the date specified in a Metafield.

As of current this is what I have including logic:

<!-- Check Today is correct -->
<p>Today: {{'now' | date: '%d-%m-%Y' }}</p>

<!-- This is the Metafield Output as a String -->
<p>Release Date: {{ product.metafields.Release-Date.preOrder }}</p>

<!-- Assign Variable "today_date" to the current date -->
{% assign today_date = 'now' | date: '%d-%m-%Y' %}
<!-- Assign Variable "pre_date" to the string of the metafield -->
{% assign pre_date = product.metafields.Release-Date.preOrder %}
{% if today_date > pre_date %}
  Today's date is greater than PreOrder Date
{% else %}
  Today's date is not greater than PreOrder Date
{% endif %}

However, even when I set the PreOrder date to 01-01-2018 it still shows the "Is greater than".

How do I correctly query this?

Kin
  • 1,435
  • 10
  • 16
Bradly Spicer
  • 2,278
  • 5
  • 24
  • 34

1 Answers1

29

You can't compare strings this way. (The dates are strings.)

You have to use the %s date filter instead.

So it will become:

{% assign today_date = 'now' | date: '%s' %}
{% assign pre_date = product.metafields.Release-Date.preOrder | date: '%s' %}
{% if today_date > pre_date %}

We use %s because it will return the current unix timestamp number instead of a string. This way you will be able to compare the different timestamps.

africola
  • 71
  • 1
  • 7
drip
  • 12,378
  • 2
  • 30
  • 49
  • This is perfect and makes a LOT of sense, I really appreciate the explanation :-) – Bradly Spicer Dec 01 '17 at 15:00
  • 2
    Note that you may need to convert this to a number for some date comparisons, so I recommend `date: '%s' | times: 1` for both assignments – cfx Sep 29 '20 at 13:39
  • @cfx in which case you'd need to convert this into a number? Can you provide an example? As far as I can tell, UNIX timestamps are always-increasing (even alphabetically as strings). For example, current UNIX timestamp is `1663582748289`. If I remove 1 from the beginning, I'll get a date in 1991. Is that the case you're talking about? – Viktor Sep 19 '22 at 10:20
  • @Viktor Sorry don't remember the example I had in mind on this... it was so long ago – cfx Sep 20 '22 at 00:39