Adding/subtracting days in Shopify's Liquid template language

Published on
2 mins read

In Shopify's Liquid template language, manipulating dates such as adding or subtracting days is not as straightforward as in other programming languages. However, with the right approach, you can achieve this by leveraging Liquid's built-in filters and variables. In this post, we’ll walk through how to work with dates and perform basic operations like adding or subtracting days.

Step-by-Step Guide

Below is an example demonstrating how to add or subtract days from the current date:

{% assign days = 4 %}

{% assign ms = days | times: 24 | times: 60 | times: 60 %}
{% assign now = 'now' | date: "%s" %}

{% assign today = now | date: "%b %d" %}
{% assign before = now | minus: ms | date: "%b %d" %}
{% assign after = now | plus: ms | date: "%b %d" %}

<div>Today: {{ today }}</div>
<div>{{days}} days before today: {{ before }}</div>
<div>{{days}} days after today: {{ after }}</div>

Result:

<!-- HTML -->
Today: Aug 29 4 days before today: Aug 25 4 days after today: Sep 02

Explaination:

  • First convert now to seconds since 1970 with filter | date: "%s".
  • Convert days range to seconds x 24 x 60 x 60
  • Use filters | minus or | plus to get the result and parse back to date format with date: "%b %d" filter

The format for Liquid date is the same as strftime