Symfony 2 setlocale (LC_ALL, 'de_DE')

人盡茶涼 提交于 2019-12-02 02:25:10

You need to enable twig intl extension (it requires enabled intl functions in php) a then you just use:

{{ event.beginAt | localizeddate('full', 'none', locale) }}

Edited:
If you want to just localized name of day, you can create your own Twig extension:

src/Acme/Bundle/DemoBundle/Twig/DateExtension.php

namespace Acme\Bundle\DemoBundle\Twig;

class DateExtension extends \Twig_Extension
{

    public function getFilters()
    {
        return array(
            new \Twig_SimpleFilter('intl_day', array($this, 'intlDay')),
        );
    }

    public function intlDay($date, $locale = "de_DE")
    {

        $fmt = new \IntlDateFormatter( $locale, \IntlDateFormatter::FULL, \IntlDateFormatter::FULL, 'Europe/Berlin', \IntlDateFormatter::GREGORIAN, 'EEEE');
        return $fmt->format($date);
    }

    public function getName()
    {
        return 'date_extension';
    }
}

Then register it in services.yml

src/Acme/Bundle/DemoBundle/Resources/config/services.yml

parameters:
    acme_demo.date_extension.class: Acme\Bundle\DemoBundle\Twig\DateExtension

services:
    acme_demo.twig.date_extension:
        class: %acme_demo.date_extension.class%
        tags:
            - { name: twig.extension }

In your Twig template you can use just:

{{ event.beginAt|intl_day }} {{ event.beginAt|date('d.m.Y') }}

In order to achieve that I used the SonataIntlBundle it exposes some twig function that are formatted with intl.

Example:

 {{ date_time_object | format_datetime(null, 'fr', 'Europe/Paris',
constant('IntlDateFormatter::LONG'), constant('IntlDateFormatter::SHORT')) }}

will output

 '1 février 2011 19:55'

I used a simpler approach since I forced the local of the php execution context and, after that, just replaced the date function by format_datetime. Remember to see the supported patterns as they differ from the strftime. You have a link on the SonataIntlBundle for that.

You can use setlocale() and strftime(), using something Symfony-specific might be overhead.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!