Events date formatting in Contao

Posted by Howard Richardson (comments: 1)

The default Contao templates just display dates and times for events in the default format from Settings, which is usually numeric and 24-hour clock. The readability of this, plus the potential for confusion from country to country, mean that the default templates are almost certainly not going to do the job for you.

The issue is further complicated by the fact that some events can span multiple days, and some events have start and end times. For each of the combinations of single/ multiple day and start / end / both times, we may need different formatting.

So I set out to write some PHP to handle all these possibilities. I wanted to write something that would work across both event reader and event listing modules, but all Contao gives you common to both are start and end datetimes. You have to detect if they span multiple days and/or have times set yourself.

I found that if a time isn't set then the end time will be 11:59pm on that day, so that became my way of detecting whether a time was set. For "full day" events, the start time is the same as the end time, so in certain cases that comparison was needed too.

In the end I came up with the following code. Formats and the branching is annotated so hopefully you can customise this easily yourself...



$dateFormatHuman="l, j<\s\u\p>S</\s\u\p> F, Y"; // set this to chosen date format
$timeFormatHuman="g:i a"; // set this to chosen time format

$oneMinuteToMidnight = date_format(date_create('2000-01-01 23:59:01'), $timeFormatHuman); // 11:59 pm in whatever format you've chosen
$startDateHuman = $this->parseDate($dateFormatHuman,$this->startTime); 

if ($startDateHuman == $endDateHuman) {
    if ($endTimeHuman == $oneMinuteToMidnight) {
    // Single day, no times
    echo "$startDateHuman";
    } else {
    if ($startTimeHuman == $endTimeHuman) {
        // Single day with start time only
        echo "$startDateHuman at $startTimeHuman"; 
        } else {
        // Single day with start and end times
        echo "$startDateHuman from $startTimeHuman &ndash; $endTimeHuman"; 
} else {
    if (($endTimeHuman == $oneMinuteToMidnight) || $startTimeHuman == $endTimeHuman) {
    // Multiple day, no times or whole days
    echo "$startDateHuman &ndash; $endDateHuman";
    } else {
    // Multiple day with times
    echo "$startDateHuman ($startTimeHuman) &ndash; $endDateHuman ($endTimeHuman)";

Go back

Add a comment

Comment by Born4digital |

Very useful Article. Events date formatting made simple. Thanks!