Extracting string and comparing with date

924 Views Asked by At

I have a string "products_2016-05-09" where 2016-05-09 is date appended in the string. I want to extract this date. If the date is minus 1 day I want to display string "products". How can I do this in liquid syntax?

2

There are 2 best solutions below

0
On

The below code worked for me:

{% assign var =  {{custom_attribute.${producttype}}} %}

{% assign words = var | split: '_' %}

{% assign yestDate = 'now' | date: "%s" | minus: 86400 | date: "%F" %}

{% assign varDate = words[1] %}

{% if varDate | convert: "date"  == yestDate %}
Dynamic String {{words[0]}}
{% else %}
sorry!
{% endif %}

 

1
On

To extract the date from the string, use the remove and split filters:

{% assign pdate = string | remove: "products_" %}
{% assign pdate = pdate | split: '-' %}

To check if that product date (pdate) is within 24 hours (86400 seconds) back, use something like this:

{% assign today = "now" | date: "%s" %}
{% assign yesterday =  today | minus: 86400 %}

{% if pdate[0] == yesterday | date: "%Y" and pdate[1] == yesterday | date: "%m" and pdate[2] == yesterday | date: "%d" %}
  Display string "products"
{% endif %}

Note: This only check if the product date is yesterday (24 hours ago from now) for a more accurate time verification, you need to do more arithmetics. You could also do all of this on the front-end using JavaScript.