简体   繁体   中英

Shopify Liquid Date Beginning of the year variables

I am looking to create variables for the following:

  1. The Beginning of this Year: Example if the date is 5/3/2021 then this would be 2021-01-05
  2. The Beginning of last year: Example if in 2021 then the date would be 2020-01-01
  3. The End of Last year: Example if in 2021 then the date would be 2020-12-31
  4. The beginning of Last Month: Example, if the date is 5/3/2021 then the this would be 2021-04-01
  5. The End of last month: Example, if the date is 5/3/2021 then this would be 2021-04-31

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

Added month example

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

NB

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM