2

I'm creating a date range where I only want to show upcoming events in the next 30 days based on a start date.

I have created my query but when I add my if statement to filter on the start date it doesn't show the upcoming events. I'm not sure what I am doing wrong.

{% set myEntryQuery = craft.entries()
    .section('events')
    .hidden('not true')
    .orderBy('eventStartDate')
%}

{% set entries = myEntryQuery.all() %}

{% for entry in entries %}
{% set start = entry.eventStartDate | date() %}
{% set currentDate = "now"|date() %}
{% set futureDate = currentDate|date_modify("+30 day")|date() %}


{% if (start >= currentDate) and (start < futureDate) %}
    <item>
        <title>{{ title }}</title>
        <link>{{ url }}</link>
        <pubDate>{{ entry.postDate|rss }}</pubDate>
        <author>CPI</author>
        <guid>{{ url }}</guid>
        <description>
        ---------
            {% if eventType == 'Events' %}
            {% else %}
            {{ eventType }}
            {% endif %}
            {% if start %}
             · {{ start }}
            {% endif %}
            {% if location %}
             · {{ location }}
            {% endif %}
        ---------
        </description>
    </item>
{% endif %}

{% endfor %}

1 Answer 1

1

To debug issues like this, you can put {% dd %} tags in your template to inspect the value of variables and find errors in your logic:

{% dd currentDate %}

The main issue with your template is that you're comparing dates as formatted strings. The date() filter returns a formatted, human-readable string (so something like 1 January 2021, the format depends on your locale). Those can't be directly compared, so the < / > checks fail.

Instead, you want to compare timestamps as DateTime objects, which is also the format used by Craft's date fields and properties by default. So removing the |date filter from your variables should fix the issue:

{% set start = entry.eventStartDate %}
{% set currentDate = now %}
{% set futureDate = currentDate|date_modify("+30 day") %}

Note the use of now instead of 'now'. The now variable is provided by Craft and contains the current timestamp as a DateTime object.


However, instead of fetching all entries and filtering them out afterwards, it would be more efficient to include the acceptable date range as a filter in your query. Something like this should work:

{% set futureDate = currentDate|date_modify("+30 day") %}
{% set myEntryQuery = craft.entries()
    .section('events')
    .hidden('not true')
    .orderBy('eventStartDate')
    .eventStartDate(['and', ">= #{now|atom}", "<= #{futureDate|atom}"])
%}

See Querying Elements with Date Fields for more information.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.