Gav
Gav

Reputation: 11

How to output days of week as a date then change every week in liquid

I am trying to output a string in Liquid (Shopify) that displays the dates for Thursday, Friday, Saturday, and Sunday for that particular week and then updates each week with the correct dates for that week.

For example, "ORDER NOW FOR COLLECTION ON 28th, 29th, 30th, and 31st."

I don't think this is a very useful approach and I'm not sure how to loop through it for all days in one week without creating a large array. Unless that is the only way?

{% assign tday = "today" | date: "%a" %}
{% assign dtime = 4 | times: 86400 %}
{% assign dday = {{ tday | plus: dtime | date: "%a"}} %}

{% if “today” == ‘Mon’ %}
    {{% ORDER NOW FOR COLLECTION ON {{dday}} %}}

{% assign tday = "today" | date: "%a" %}
{% assign dtime = 3 | times: 86400 %}
{% assign dday = {{ tday | plus: dtime | date: "%a"}} %}

{% elseif “today” == ‘Tue’ %}
    {{% ORDER NOW FOR COLLECTION ON {{dday}} %}}

{% assign tday = "today" | date: "%a" %}
{% assign dtime = 2 | times: 86400 %}
{% assign dday = {{ tday | plus: dtime | date: "%a"}} %}

{% elseif “today” == ‘Wed’ %}
    {{% ORDER NOW FOR COLLECTION ON {{dday}} %}}

Upvotes: 0

Views: 984

Answers (1)

kamenarov
kamenarov

Reputation: 341

It's easy when you are using only one time format. In my approach, I'm using only a timestamp.

Firstly I get the number of the current day, which is 6 for Saturday.

The current day variable is minus 1 because most formats are suitable to calculate the days from 0 to 6 (like array), not from 1 to 7.

After that, I'm doing a calculation to get the Monday timestamp.

Seconds in one day multiplied by the current number of the day, I'm multiplying that by -1 to make the negative number and when I add the current day to this, the result will be Monday.

86400*5=518400
518400*-1=-518400 // Negative 5 days
-518400+1637441515...

And We'll get the Monday timestamp.

The Monday variable can be a little messy for you, but I'm trying to use just one line to do all the calculations.

In the end, I'm doing the calculation by adding the seconds for the days to the Monday timestamp.

Here is the code:

{%- assign day_in_seconds = 86400 -%}
{%- assign time = 'now' | date: '%s' | plus: 0 -%}
{%- assign current_day = time | date: '%u' | minus: 1 -%}
{%- assign monday = day_in_seconds | times: current_day | times: -1 | plus: time -%}

{%- for i in (3..6) -%}
    {%- assign day = day_in_seconds | times: i | plus: monday  -%}
    

    {{- day | date: "%a, %b %d, %y" -}}
    <br />

{%- endfor -%}

The example is based on Saturday as a day, but they will be relevant for the week.

Upvotes: 1

Related Questions