Yii 1.1: Localized version of CFormatter

5 followers

Update!

Since Yii 1.1.14, a CLocalizedFormatter is available.

To replace the application component 'format', which is registered by CApplication by default, you can put this in your application 'components' config:

'format' => array('class' => 'CLocalizedFormatter'),

Original article

The default CFormatter (accessible through Yii::app()->format) is not locale aware, unfortunately. Until it is, here is a quick and easy way to localize it, by extending the default class.

Put this file in your protected/components.

class LocalizedFormatter extends CFormatter
{
    /**
     * Initializes this class.
     */
    public function init()
    {
        switch (Yii::app()->language) {
            case 'nl':
                $this->dateFormat = 'd-m-Y';
                $this->timeFormat = 'H:i:s';
                $this->datetimeFormat = 'd-m-Y H:i:s';
                $this->numberFormat = array(
                    'decimals'=>null,
                    'decimalSeparator'=>',',
                    'thousandSeparator'=>'.'
                );
                $this->booleanFormat = array('Nee', 'Ja');
                break;
            // Add more language cases according to your needs        
        }
    }
}

And set the following in your config/main.php

'components' => array(
    (...)
    'format' => array(
        'class' => 'LocalizedFormatter',
    ),
    (...)
),

Total 2 comments

#10413 report it
marcovtwout at 2012/10/26 08:04am
Re: May be needed use CLocale (date, time, number) for extending CFormatter?

Combining CFormatter with CLocale is probably a solution that will make it's way into the core. This is for those with less time on their hands. ;)

#10411 report it
Yiivgeny at 2012/10/26 07:54am
May be needed use CLocale (date, time, number) for extending CFormatter?

subj.

Leave a comment

Please to leave your comment.

Write new article