CODE

Liquid Date Differences

ESTIMATE 3-MINUTE READ

Dates Compound Mathematics

It seems like a simple request. Something expires (or begins) in so many days. Let’s say 90 days. In theory, you should be able to add 90 to the publication date. When that date arrives, the magic happens. But that is far from the case.

Although a date string includes numerals, a date is not a number. We perform complex permutations in our heads to understand that 1/13/2023 is 13 days greater than 12/31/2022. Remove the slashes and it doesn’t seem possible. By that math, the difference is 11,179,999 days!

What if we use the year-month-day format {% assign now_ymd = 'now' | date: '%Y%m%d' | abs %}? Then 20230113 is greater than 20221231, but the difference is 8,882 days. The only benefit of YYYYMMDD is a comparison of equal to or greater than a value—not delta days.

Liquid Date Difference

Days and months can appear in different orders, and years may or may not include the century. Dates can also include time, formatted in various ways within different time zones. As you can see, determining 90 days in the future can seem like a solution requiring an eternity.

To remedy the date dilemma, there are server-side plugins that system administrators install (dateutil). This level of control may not be accessible to e-commerce marketplace merchants or end users.

How to Add Days to Dates in Shopify

Fortunately, Shopify provides access to the top layer of code using the Liquid programming language. For the ones willing to sacrifice theme upgrades, there is a way to reasonably calculate day differences.

Caution: Modifying Liquid code may invalidate your theme for future updates by the developer. Anything you add will require manual migration to a different theme, with possible incompatibility.

The key is to convert both dates to a Unix to timestamp integers (date: '%s') using Python strftime. Subtract the timestamps, and divide the value by 86400 (number of seconds within 24 hours) to turn it into a number of days. Then compare to see if the difference is greater than 90 (or whatever value you require).

Login For Code

Shopify has created its own interface for merchants to access metafields, which have been available for some time via third-party apps.

The blog metafield is where you can store the amount of days for comparison. {{blog.metafields.custom.expiration_days}} This way, if you have multiple blogs, each can have its own expiration date, when applicable.

Join Discussion