Translating the day and month of a date with PHP

Published on 2022-04-12 • Modified on 2022-04-12

This snippet shows how to translate the day and month of a date with PHP. We use the intl extension and its IntlDateFormatter class. In the first example, we use a custom pattern, and in the second, we use predefined constants. Click on the "more on the web" button to see the table of all available patterns. Click here to check the output of the same snippet with the French locale 🇫🇷.


<?php

declare(strict_types=1);

namespace App\Controller\Snippet;

use Symfony\Component\HttpFoundation\Request;

/**
 * I am using a PHP trait to isolate each snippet in a file.
 * This code should be called from a Symfony controller extending AbstractController (as of Symfony 4.2)
 * or Symfony\Bundle\FrameworkBundle\Controller\Controller (Symfony <= 4.1).
 * Services are injected in the main controller constructor.
 */
trait Snippet197Trait
{
    public function snippet197(Request $request): void
    {
        echo 'Locale : '.$request->getLocale().PHP_EOL;
        echo 'Timezone : '.date_default_timezone_get().PHP_EOL;
        $dateTime = new \DateTime();

        $pattern = 'EEEE (d) MMMM yyyy';
        $fmt = new \IntlDateFormatter($request->getLocale(), 0, 0, null, null, $pattern);
        echo $fmt->format($dateTime).PHP_EOL;

        $fmt = new \IntlDateFormatter(
            locale: $request->getLocale(),
            dateType: \IntlDateFormatter::FULL,
            timeType: \IntlDateFormatter::FULL
            // we don't use a custom pattern here
        );
        echo $fmt->format($dateTime);

        // That's it! 😁
    }
}

 Run this snippet  More on Stackoverflow   Read the doc  More on the web  Random snippet

  Work with me!