Bug Hero Image

Date Bug

I recently updated my photo blog (desperately needs a redesign) from Craft 2.x to Craft 3.0.36 (as of writing this blog post).  Yesterday I noticed that the archives template had an issue when trying to view February in any year. It would, inexplicably, take me to March.

The code that was causing this issue is:

{# all entries sorted by year/month #}
 {% set allEntries = craft.entries.section('photoblog').limit(null).orderBy('postDate desc').all() %}

  <div class="years">
    {% for year, entriesInYear in allEntries | group("postDate|date('Y')") %}
        <div class="col-sm-3 col-xs-4" data-mh="years">
          <h3>{{ year }}</h3>
          <ul class="list-unstyled">
          {% for month, entries in entriesInYear | group("postDate|date('F')" ) |  reverse %}
              <li><a href="/calendar/{{ year }}/{{ month|date('m') }}">{{ month }}&nbsp;({{ entries|length }})</a></li>
          {% endfor %}
    {% endfor %}

Specifically this bit {{ month|date('m') }} is subject to a php bug when the current day is a number higher than the month being viewed has. Yesterday was December 30th and the 30th does not exist in February.

Since twig is just a wrapper for php code that means that twig dates are subject to the same bug.

The solution to this is to simply add the year to the date which then  according to the bug linked above forces the month to use the first day of the month and not the current day. And the working code is here:

  {# need month to include year to avoide a bug with short months when the current day is 30 or 31 i.e. february #}
  {% set thisMonth = month ~ '-' ~ year %}

  <a href="/calendar/{{ year }}/{{ thisMonth|date('m') }}">{{ month }}&nbsp;({{ entries|length }})</a>

Now all my links are working correctly. Honestly I"m surprised that php hasn't fixed this bug in the last 9.5 years but at least there's an easy fix. Got pointed in the right direction on this Stack Exchange thread.