I’m working with Shopify liquid templates and need help figuring out how to calculate the difference in days between two dates.
Right now I have this code that gets me both dates:
{% assign item_launch_date = item.created_at | date: "%a, %b %d, %y" %}
{% assign today_date = 'now' | date: "%a, %b %d, %y" %}
This shows me when an item was added and today’s date. What I want to do is display to customers how many days ago the item was added to the store.
I’ve been looking through liquid documentation and searching online but can’t find a clear way to do this math with just liquid code. Is there a way to subtract these dates and get the number of days using only liquid syntax without any external scripts?
yeah, this works but heads up - liquid rounds down automatically, so day 0 = “today”. I usually throw in a conditional to display “new” instead of “0 days ago” since it looks cleaner. if you want hours/minutes, just skip the division and use seconds_difference directly.
Convert both dates to Unix timestamps first, then do the math. Don’t use the date filter for formatting until after you’ve calculated everything. Here’s what works:
{% assign item_timestamp = item.created_at | date: ‘%s’ %}
{% assign current_timestamp = ‘now’ | date: ‘%s’ %}
{% assign seconds_difference = current_timestamp | minus: item_timestamp %}
{% assign days_difference = seconds_difference | divided_by: 86400 %}
The %s format gets you Unix timestamps in seconds. Subtract them, divide by 86400 (seconds in a day), and you’ve got your days difference. I used this exact method for showing product age in a store project - worked perfectly. Just heads up: this gives whole numbers and rounds down.
You’re right about using Unix timestamps, but I’d store the result in a variable if you’re using it multiple times - better performance that way:
{% assign launch_timestamp = item.created_at | date: '%s' | plus: 0 %}
{% assign now_timestamp = 'now' | date: '%s' | plus: 0 %}
{% assign days_old = now_timestamp | minus: launch_timestamp | divided_by: 86400 %}
The plus: 0 converts to integer and helps with calculation accuracy. This method’s been reliable across different Shopify themes for me. Just watch out for timezone handling - timestamps default to UTC, so you might need to adjust your display logic if your store runs in a specific timezone.