How to display entries with a custom date field within month I've got a date field, and I'm grabbing the month and year from the url. What I'm after is to display all the events within the month, but for some reason I can't get this to work

{% set firstDayOfMonth = month ~ "/1/" ~ year|date("U") %} // returns the 1st day of the month in unixtime

{% set daysInThisMonth = firstDayOfMonth|date('t') %}
{% set lastDayOfMonth = month ~ "/" ~ daysInThisMonth ~ "/" ~ year|date("U") %} // returns the last day of the month in unixtime

{% set thisMonthsEvents = craft.entries.section('events').eventDate('and', '&gt;= ' ~ firstDayOfMonth, '&lt;= ' ~ lastDayOfMonth) %}

{% if thisMonthsEvents | length %}
    some events
{% else %}
    no events
{% endif %}


Any ideas? firstDayOfMonth and lastDayOfMonth return dates fine, but no matter how I format them, the result is no entries returned. For example, firstDayOfTheMonth could output "2014-6-01" and lastDayOfMonth could output "2014-6-30", and I've got an event with an eventDate of 18th June 2014, but nothing is being returned.
Solution 1:

The problem with your code is, that you apply the date filter exclusively to the year variable:


  {% set firstDayOfMonth = month ~ "/1/" ~ year|date("U") %}


To get this right you have to first compose your "datetime string" and then apply the filter to the string as a whole:

{% set firstDayOfMonth = (month ~ "/1/" ~ year)|date("U") %}


That's also the reason why it works for you to apply it inside the query.

.

Solution 2:

You don't need to pass a unix datetime formated string to your query, a string in format "Y-m-d" is just fine:

{% set firstDayOfMonth = year ~ "-" ~ month ~ "-01" %}
{% set daysInThisMonth = firstDayOfMonth|date('t') %}

{% set lastDayOfMonth = year ~ "-" ~ month ~ "-" ~ daysInThisMonth %}

{% set thisMonthsEvents = craft.entries.section('events').eventDate('and', '&gt;= ' ~ firstDayOfMonth, '&lt;= ' ~ lastDayOfMonth) %}