Formatting a date with the IntlDatePatternGenerator PHP class

Published on 2024-08-03 • Modified on 2024-08-03

This snippet shows how to format a date using the IntlDatePatternGenerator PHP class. We define a pattern, and then a "best" pattern is calculated depending on a locale. Finally, we can format the date using this locale pattern.


<?php

declare(strict_types=1);

namespace App\Controller\Snippet;

/**
 * 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 Snippet312Trait
{
    public function snippet312(): void
    {
        $datePattern = 'YYYYMMdd';
        $today = \DateTimeImmutable::createFromFormat('Y-m-d', '2024-08-22');
        $dePg = new \IntlDatePatternGenerator('de_DE');
        $pattern = $dePg->getBestPattern($datePattern);
        echo 'de_DE: ', \IntlDateFormatter::formatObject($today, $pattern, 'de_DE'), PHP_EOL;

        $enUsPg = new \IntlDatePatternGenerator('en_US');
        $pattern = $enUsPg->getBestPattern($datePattern);
        echo 'en_US: ', \IntlDateFormatter::formatObject($today, $pattern, 'en_US');

        // That's it! 😁
    }
}

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

  Work with me!