Adding a date to an article

Good morning. I’m creating a blog and I want to add a date to my articles.
I do it this way:

<?= $page->published()->toDate('d m Y') ?>

and I get this: 21 09 2023

I would like to get:

21 lipiec, 2023

How to do it?

One more question.

Is it good:

<?= $page->published()->toDate('d m Y') ?>

should it be?

<?= $page->published()->toDate('d.m.Y' ) ?>
1 Like

Hello,

I had the same question and got it working with this for the blog page (where the articles are listed) :

<?= $article->date()->toDate('Y-m-d') ?>

and this on the article itself :

<?= $page->date()->toDate('Y-m-d') ?>

and refered to this to set the correct date format depending on my config : date | Kirby CMS

Hope it can help someone.

Have a nice day.

On my setup I had no access to some PHP extension to help with formatting date. Maybe it’s imperfect or not the way it should be done but it worked for me, as I had the exact same need as you. So here it is, for anyone looking for different dates implementations :

Created file site/models/default.php

class DefaultPage extends Page {
    public function formatDate( $dateField = 'published' ) {

        // Check if the date is empty or invalid
        if (!$dateField) return '';
        
        // Create a DateTime object from the date field (published is assumed)
        $dateTime = new DateTime($dateField);

        // Define translations for month names
        $months = [
            'en' => ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
            'fr' => ['janvier', 'février', 'mars', 'avril', 'mai', 'juin', 'juillet', 'août', 'septembre', 'octobre', 'novembre', 'décembre'],
            // Add more languages as needed
        ];

        // Get the current language/locale from Kirby (fr, en, etc)
        $locale = kirby()->language()->code();
        
        // Ensure the locale exists in the months array (defaults to fr)
        if (!array_key_exists($locale, $months)) {
            $locale = 'fr';
        }

        $monthIndex = (int)$dateTime->format('n') - 1; // Get the month index (0-based)

        $monthName = $months[$locale][$monthIndex]; // Get the corresponding string

        $formattedDate = $dateTime->format('j') . ' ' . $monthName . ' ' . $dateTime->format('Y');

        return $formattedDate;
    }
}

then in my site/templates file:

<span class="post-meta"><?= t('published', 'Publié le ') . $page->formatDate( $page->published() ) ?></span>