D
D
Daniil Sidorov2021-02-15 23:46:32
Yii
Daniil Sidorov, 2021-02-15 23:46:32

How to set language for Carbon date localization?

Hello. I am engaged in the internalization of the project on Yii2. There was a need to translate dates and times. I use Yii2 Locale URLs for internalization and Carbon for working with dates .

Previously, when the language was only Russian, I did it this way ( web/index.php ):

<?php

use Carbon\Carbon;

defined('YII_DEBUG') or define('YII_DEBUG', true);
defined('YII_ENV') or define('YII_ENV', 'dev');

require __DIR__ . '/../vendor/autoload.php';
require __DIR__ . '/../vendor/yiisoft/yii2/Yii.php';

$config = require __DIR__ . '/../config/web.php';

Carbon::setLocale('ru');

(new yii\web\Application($config))->run();


The decision even then seemed to me quite a crutch. And now it will not work at all, because. I want to pass a Yii::$app->language value to the setLocale function , but it won't be generated yet. I tried to create a component that will set the translation language. To do this, I wrote the following in the config:

'as afterRequest' => [
        'class' => 'app\components\CarbonLang',
    ],

And in the CarbonLang component:
class CarbonLang extends \yii\base\Behavior
{
    public function events()
    {
        return [
            Application::EVENT_AFTER_REQUEST => 'setCarbonLocale'
        ];
    }

    public function setCarbonLocale($event)
    {
        Carbon::setLocale(Yii::$app->language);
    }
}


Yii::$app->language stores the correct language (ru) value. When you switch the language, it also changes. But the translations do not work, they are always displayed in English.

Please tell me in which direction to move in order to solve this problem. Thank you!

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question