Localize date names in Kirby

Kirby Howto: Localizing Date, Week and Month Names in Kirby 2

Kirby Howto: Localizing Date, Week and Month Names in Kirby 2

Fun with displaying month and day names in local language

We have been using the file-based CMS Kirby for several years now and are quite satisfied with it. Most things work intuitively - and when things get a bit more difficult, you can usually find good answers in the Kirby forum.

However, even with this software "oddities" exist where intuition does not help much. The correct localization of dates and times is one of those areas - especially if you want to display day and month names written out in local language.

There are essentially three implementation options:

1) Do-it-yourself

A technically simple solution would be to build your own translation using the l()-function and arrays with the date and day names. But with this you are entirely on your own with updates (e.g. adding a new language) or maintenance. We therefore call this option only for the sake of completeness - from our point of view there are better alternatives.

2) Use IntlDateFormatter from the PHP 'intl' extension

The PHP class "IntlDateFormatter" can easily be used to get the localized month and day names and supports a variety of languages.

First, create a formatter object:

<?php $formatter = datefmt_create($language->code(), IntlDateFormatter::LONG, IntlDateFormatter::NONE); >?

and then uses this to localize your data:

<?php echo datefmt_format( $formatter, $page->date()); ?>

The standard formatting functions for date (IntlDateFormatter::LONG in the example above) and time (IntlDateFormatter::NONE in the example) are very flexible - certainly good enough for our own purposes...

Attention, two conditions must be met for this approach:

  1. PHP 5.3 or later. But this should be the case by now, for the most part.
  2. The PHP extension "intl" must be included. Unfortunately this is not the case in macOS' stock PHP.

3) Use "strftime" for date formatting

Kirby 2.1 introduced a configuration option that makes it even easier to output correctly formatted time and dates by defining a handler in

site/config/config.php
:

c::set('date.handler', 'strftime');

Unfortunately work is not done yet, as the formatting parameters for date and strfdate are different!
E.g. a date using written-out month names in US English would need to change from

'F jS, Y'
to
'%B %e%O, %Y'
.

Attention: This also applies to time stamps, e.g. from the sitemap. These use a formatting according to ISO 8601, e.g.

date('c')
. This must be rewritten to e.g.
date('%FT%TZ')
.

Conclusion:

  • For Kirby version 2.1 or higher, we would recommend using
    strftime
    to format dates.
  • For earlier versions, we believe the
    IntlDateFormatter
    is the best choice.

Related links: