How to compare dates in Shopify?
In Shopify, the dates are strings so you can’t compare strings in the usual way. With Shopify liquid, you have to use the %s date filter to convert the date time to Unix epoch time.
The following source code will convert a specific day:
1 | {% assign specific_date = '2019-01-08' | date: '%s' %} |
The following source code will convert current date:
1 | {% assign today_date = 'now' | date: '%s' %} |
And now you can use the operators: >, <, >=, <=.
1 2 3 4 5 | {% if specific_date < today_date %} //Code {% else %} //Code {% endif %} |
Thank you very much. It’s great.
I believe it is still comparing timestamp STRINGS so any timestamp that starts with an number higher than today’s timestamp, even if it’s 50 years ago, will always be greater than today. Suggestion to use a secondary filter, plus: 0, that coerces the timestamp to an integer.
{% assign today_date = 'now' | date: '%s' % | plus: 0 }