Search code examples
datedatetimeif-statementjekyllliquid

Liquid template logic to check if a date has no time component? String comparison fails


I'm trying to get a Liquid condition to run only if page.date has a defined time.

Let's say page.date is "2019-07-17 00:00:00 -0700".

I found out that the 12-hour (%r) time is 12am by default, so I tried this hack (I'm not too worried about a time actually being set by the user to 12:00:00 sharp, causing false positives):

{% if page.date | date: "%r" != "12:00:00 AM" %}
    <p>The page's date has a time.</p>
{% else %}
    <p>The page's date has no time.</p>

The above block outputs "The page's date has a time.", which is untrue according to my condition (that 12am = "no time").

I also tried the following, with and without | json pipes to the right of the date formatter:

  • {% if page.date | date: "%T" != "00:00:00" %}

  • {% if page.date | date: "%R" != "00:00" %}

Rendering all these formats to a page validates the values I've put in these conditionals, but my string comparisons are still incorrect. Is there a way to do this in Liquid?


Solution

  • You cannot filter in a condition. {% if page.date | date: "%r" != "12:00:00 AM" %} is producing an error.

    You can assign, then compare :

    {% assign time = page.date | date: "%r" %}
    
    {% if time != "12:00:00 AM" %}
        <p>The page's date has a time.</p>
    {% else %}
        <p>The page's date has no time.</p>
    {% endif %}