How to Display Dates Nicely

Problem

Sometimes, events dates span more than one month, and we need a way to output them nicely. For example, an event that runs from January 27 to February 2.

This macro will do the trick.

Solution

Our macro takes two values, representing the start and end dates of the event. There are three possible conditions:

  • No end date, or start and end date are the same. That means it’s a single day event.
  • Start date and end date are in the same month, like Jan 15-16.
  • Start date and end date are in different months, like Jan 28 - Feb 2.
{% macro eventDater(startDate, endDate) %}

    {% if endDate|length == 0 or startDate|date('Y-m-j') == endDate|date('Y-m-j') %}
    {# No end date *or* start date and end date are the same - single day event #}
        <time datetime="{{ startDate|date('Y-m-j') }}">{{ startDate|date('F j, Y') }}</time>
    {% elseif endDate|length and startDate|date('m') == endDate|date('m') %}
        {# Has end date *and* start date and end date are in the same month, i.e., Jan 15-16 #} 
        <time datetime="{{ startDate|date('Y-m-j') }}">
            {{ startDate|date('F') }} {{ startDate|date('j') }}-{{ endDate|date('j') }}, {{ startDate|date('Y') }}
        </time>   
    {% elseif endDate|length and startDate|date('m') != endDate|date('m') %}
    {# Has end date but start date and end date are in different month, i.e., Jan 31 - Dec 1 #} 
        <time datetime="{{ startDate|date('Y-m-j') }}">
            {{ startDate|date('F') }} {{ startDate|date('j') }} - {{ endDate|date('F') }} {{ endDate|date('j') }}, {{ startDate|date('Y') }}
        </time>
    {% endif %}

{% endmacro %}

Discussion

And there it is. If you want the dates to output differently, like European format, just edit the date filters.