dateshopifyarticle

How to prevent duplicate blog post dates in shopify


I have a blog with posts on a shopify website. I want to get all the publication dates of posts, and I do it like this:

{% for article in blog.articles %}
   {{ article.created_at }}                 
{% endfor %}

And this is the output result:

2022-02-01 14:50:06
2022-01-25 05:25:33
2022-01-25 05:24:48

The result shows that there are two posts with the date 2022-01-25 and one post with the date 2022-02-01. But all these dates have different seconds and minutes.

I want to remove seconds and minutes by setting the format to date: "%B %Y":

{{ article.created_at | date: "%B %Y" }}

And in the end I get this result:

February 2022
January 2022
January 2022

Now the question is: How do I prevent duplicate dates with the same format date: "%B %Y"?

I can easily solve this problem with javascript, but I want to know if it's possible to solve this problem using only shopify features.

I will be glad to any answer. Thanks!


Solution

  • You can store all the dates in as string

    {%- capture dates -%}
    {%- for article in blog.articles -%}
       {{ article.created_at | date: "%B %Y" }},            
    {%- endfor -%}
    {%- endcapture -%}
    

    And split and uniq the values to get only the unique ones:

    {% assign unique_dates = dates | split: ',' | uniq %}
    

    This will remove any values that are repeating.

    Hope this is what you are looking for.