【问题标题】:Shopify Liquid Date Beginning of the year variablesShopify Liquid 日期年初变量
【发布时间】:2021-07-26 05:22:49
【问题描述】:

我希望为以下内容创建变量:

  1. 今年年初:例如,如果日期是 2021 年 5 月 3 日,那么这将是 2021-01-05
  2. 去年年初:例如,如果在 2021 年,那么日期将是 2020-01-01
  3. 去年年底:例如,如果在 2021 年,那么日期将是 2020-12-31
  4. 上个月的开始:例如,如果日期是 2021 年 5 月 3 日,那么这将是 2021-04-01
  5. 上个月月底:例如,如果日期是 2021 年 5 月 3 日,那么这将是 2021-04-31

我有以下内容,它按预期显示,但我不确定如何使用流式语法将这些分配为变量。

{% assign start_date = 'now' | date: '%s' %}

{% assign start_date_year = 'now' | date: '%Y' %}

这会显示预期的日期以及当前日期的年份。但是当我执行以下操作时,我没有得到 2020 年:

{% assign yoy_start = start_date_year | minus: 1 | date: '%Y-%m-%d' %}

【问题讨论】:

    标签: date shopify liquid


    【解决方案1】:

    单独的年份不是date 格式可以解析的有效日期字符串。您需要“2020 年 1 月 1 日”之类的内容。

    这是一种使用日期格式的方法

    {% 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
    

    但这样做可能更容易

    {% liquid
    assign this_year = 'now' | date: '%Y' 
    assign last_year_start = this_year | minus: 1 | append: '-01-01'
    %}
    
    {{ last_year_start }}
    // 2020-01-01
    
    

    添加月份示例

    这是一个可以找到上个月的示例(并且说明上个月是上一年)

    {% 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
    
    

    注意

    请注意,Shopify 会缓存呈现的主题视图,因此使用“现在”有时会产生意外结果。

    【讨论】:

    • 谢谢!这行得通!最后一件事,我正在尝试根据当前月份引入上个月。我使用与去年相同的逻辑构建了这个,但是当涉及到个位数月份时,月份之前不会有“0”,如果我硬编码 0,那么两位数月份看起来像 012,所以我不想那样做。 {% liquid assign this_month = 'now' | date: '%m' assign last_month = this_month | minus: 1 assign last_month_start = this_year | append: '-'| append: last_month | append: '-01' %} {{ last_month_start }} 2021-4-01
    • 这有点毛骨悚然,因为你必须考虑跨年,但我已经用一个例子更新了我的答案来处理几个月。我通过创建一个包含正确数字的月份数组,然后使用查找来做到这一点。因此,如果是一月减去一个月,那么它也会从年份中减去 1。这很粗糙,但它很有效,因为 12 个月是可预测的,你必须采取不同的策略来处理几天。
    猜你喜欢
    • 2020-10-28
    • 1970-01-01
    • 2015-12-10
    • 1970-01-01
    • 2012-11-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-21
    相关资源
    最近更新 更多