I am looking to create variables for the following:
I have the following and it shows as expected but I am not sure how I can get these assigned as variables using the liquid syntax.
{% assign start_date = 'now' | date: '%s' %}
{% assign start_date_year = 'now' | date: '%Y' %}
This shows the date as expected and the year of the current date as well. But when I do the following I do not get the year 2020:
{% assign yoy_start = start_date_year | minus: 1 | date: '%Y-%m-%d' %}
The year alone is not a valid date string that can be parsed by the date
format. You need something like "Jan 1st, 2020".
Here's a way to do it with the date format
{% liquid
assign this_year = 'now' | date: '%Y'
assign last_year = this_year | minus: 1
assign last_year_start = "Jan 1st, " | append: last_year | date: '%Y-%m-%d'
%}
{{ last_year_start }}
// 2020-01-01
But it might be easier to just do
{% liquid
assign this_year = 'now' | date: '%Y'
assign last_year_start = this_year | minus: 1 | append: '-01-01'
%}
{{ last_year_start }}
// 2020-01-01
Here's an example that can find the previous month (and accounts for the previous month being in a previous year)
{% liquid
assign list_of_months = "12,01,02,03,04,05,06,07,08,09,10,11,12" | split: ","
assign last_month_index = 'now' | date: '%m' | minus: 1
assign last_month_year = 'now' | date: '%Y'
if last_month_index < 1
assign last_month_year = last_month_year | minus: 1
endif
assign last_month_start = last_month_year | append: '-' | append: list_of_months[last_month_index] | append: '-01'
%}
{{ last_month_start }}
// 2020-04-01
Note that Shopify caches the rendered theme view, so using 'now' can sometimes produce unexpected results.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.