version française

Date localization in Kirby with php 8.1

I try to, everytime I struggle to do something — say, for example, configure my library with calibre web —, take the time to document it here, so that I can easily find the information later, and potentially help other people.

So here's a small article to document today's problem:

I display the publication day at the top of every article, with this format: « 2 février 2025 ». By default, in PHP, dates are written in english.

Here's the way I was displaying date with the month in French until now:

<?php setlocale(LC_TIME, "fr_FR");
$laDate = $page->date()->toDate();
echo utf8_encode(strftime("%e %B %Y", $laDate)); ?>

To be honest, I find it already quite verbose to just display the date in one language 🤐

The problem is that, starting with PHP 8.1, strftime est deprecated, so I have to change my method. Here's the solution I found after way too many tests and errors:

  1. In the Kirby conf file, add this option (cf. the doc) :

    'date'  => [
     'handler' => 'intl'
    ]


  2. Then, in your hosting configuration, activate the php intl extension. With Alwaysdata, you'll have to add it in the custom php.ini of your site (cf. the doc) :
    extension = intl.so

  3. Finally, in your code, do something like that (cf. this and that) :

    $laDate = $page->date()->toDate();
    $formatter = new IntlDateFormatter('fr_FR', IntlDateFormatter::SHORT, IntlDateFormatter::SHORT);
    $formatter->setPattern('d MMMM yyyy');
    echo $formatter->format($laDate);
  4. If you want to use more than one language on your site, you'll just have to modify this line to use automatically the current locale:

    $formatter = new IntlDateFormatter($kirby->language()->locale(LC_ALL),
    IntlDateFormatter::SHORT, IntlDateFormatter::SHORT);

There's probably a better way to do that, more elegant, more robust, but this works, so that's good enough for me for now! I'll update this article if I find a better solution.