简体   繁体   English

Shopify 流动日期 年初变量

[英]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今年年初:例如,如果日期是 2021 年 5 月 3 日,那么这将是 2021-01-05
  2. The Beginning of last year: Example if in 2021 then the date would be 2020-01-01去年年初:例如,如果在 2021 年,那么日期将是 2020-01-01
  3. The End of Last year: Example if in 2021 then the date would be 2020-12-31去年年底:例如,如果在 2021 年,那么日期将是 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上个月的开始:例如,如果日期是 2021 年 5 月 3 日,那么这将是 2021-04-01
  5. The End of last month: Example, if the date is 5/3/2021 then this would be 2021-04-31上个月末:例如,如果日期是 2021 年 5 月 3 日,那么这将是 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:但是当我执行以下操作时,我没有得到 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.单独的年份不是可以通过date格式解析的有效日期字符串。 You need something like "Jan 1st, 2020".您需要类似“2020 年 1 月 1 日”的内容。

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.请注意,Shopify 会缓存渲染的主题视图,因此使用“现在”有时会产生意想不到的结果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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