Files
yii2/docs/guide/output-formatting.md
2015-05-31 23:19:31 -04:00

12 KiB
Raw Blame History

Data Formatting

To display data in a more readable format for users, you may format them using the formatter application component. By default the formatter is implemented by yii\i18n\Formatter which provides a set of methods to format data as date/time, numbers, currencies, and other commonly used formats. You can use the formatter like the following,

$formatter = \Yii::$app->formatter;

// output: January 1, 2014
echo $formatter->asDate('2014-01-01', 'long');
 
// output: 12.50%
echo $formatter->asPercent(0.125, 2);
 
// output: <a href="mailto:cebe@example.com">cebe@example.com</a>
echo $formatter->asEmail('cebe@example.com'); 

// output: Yes
echo $formatter->asBoolean(true); 
// it also handles display of null values:

// output: (Not set)
echo $formatter->asDate(null); 

As you can see, all these methods are named as asXyz(), where Xyz stands for a supported format. Alternatively, you may format data using the generic method yii\i18n\Formatter::format(), which allows you to control the desired format programmatically and is commonly used by widgets like yii\grid\GridView and yii\widgets\DetailView. For example,

// output: January 1, 2014
echo Yii::$app->formatter->format('2014-01-01', 'date'); 

// you can also use an array to specify parameters for the format method:
// `2` is the value for the $decimals parameter of the asPercent()-method.
// output: 12.50%
echo Yii::$app->formatter->format(0.125, ['percent', 2]); 

Configuring Formatter

You may customize the formatting rules by configuring the formatter component in the application configuration. For example,

return [
    'components' => [
        'formatter' => [
            'dateFormat' => 'dd.MM.yyyy',
            'decimalSeparator' => ',',
            'thousandSeparator' => ' ',
            'currencyCode' => 'EUR',
       ],
    ],
];

Please refer to yii\i18n\Formatter for the properties that may be configured.

Formatting Date and Time Values

The formatter supports the following output formats that are related with date and time:

The default date and time formats used for the yii\i18n\Formatter::asDate(), yii\i18n\Formatter::asTime(), and yii\i18n\Formatter::asDatetime() methods can be customized globally by configuring
yii\i18n\Formatter::dateFormat, yii\i18n\Formatter::timeFormat, and yii\i18n\Formatter::datetimeFormat.

You can specify date and time formats using the ICU syntax. You can also use the PHP date() syntax with a prefix php: to differentiate it from ICU syntax. For example,

// ICU format
echo Yii::$app->formatter->asDate('now', 'yyyy-MM-dd'); // 2014-10-06

// PHP date()-format
echo Yii::$app->formatter->asDate('now', 'php:Y-m-d'); // 2014-10-06

When working with applications that need to support multiple languages, you often need to specify different date and time formats for different locales. To simplify this task, you may use format shortcuts (e.g. long, short), instead. The formatter will turn a format shortcut into an appropriate format according to the currently active yii\i18n\Formatter::locale. The following format shortcuts are supported (the examples assume en_GB is the active locale):

  • short: will output 06/10/2014 for date and 15:58 for time;
  • medium: will output 6 Oct 2014 and 15:58:42;
  • long: will output 6 October 2014 and 15:58:42 GMT;
  • full: will output Monday, 6 October 2014 and 15:58:42 GMT.

Time Zones

When formatting date and time values, Yii will convert them to the default yii\i18n\Formatter::timeZone. Therefore the input value is assumed to be in UTC unless a time zone is explicitly given. For this reason it is recommended to store all date and time values in UTC, preferably as a UNIX timestamp, which is always UTC by definition. If the input value is in a time zone different from UTC, the time zone has to be stated explicitly like in the following example:

// assuming Yii::$app->timeZone = 'Europe/Berlin';
echo Yii::$app->formatter->asTime(1412599260); // 14:41:00
echo Yii::$app->formatter->asTime('2014-10-06 12:41:00'); // 14:41:00
echo Yii::$app->formatter->asTime('2014-10-06 14:41:00 CEST'); // 14:41:00

Since version 2.0.1 it is also possible to configure the time zone that is assumed for timestamps that do not include a time zone identifier like the second example in the code above. You can set yii\i18n\Formatter::defaultTimeZone to the time zone you use for data storage.

Note: As time zones are subject to rules made by the governments around the world and may change frequently, it is likely that you do not have the latest information in the time zone database installed on your system. You may refer to the ICU manual for details on updating the time zone database. See also: Setting up your PHP environment for internationalization.

Formatting Numbers

For formatting numeric values the formatter class provides the following methods:

The format for number formatting can be adjusted using the yii\i18n\Formatter::decimalSeparator and yii\i18n\Formatter::thousandSeparator which are set by default according to the locale.

For more advanced configuration, yii\i18n\Formatter::numberFormatterOptions and yii\i18n\Formatter::numberFormatterTextOptions can be used to configure the internally used NumberFormatter class

For example, to adjust the maximum and minimum value of fraction digits, you can configure yii\i18n\Formatter::numberFormatterOptions property like the following:

'numberFormatterOptions' => [
    NumberFormatter::MIN_FRACTION_DIGITS => 0,
    NumberFormatter::MAX_FRACTION_DIGITS => 2,
]

Other formatters

In addition to date, time and number formatting, Yii provides a set of other useful formatters for different situations:

null-values

For values that are null in PHP, the formatter class will print a placeholder instead of an empty string which defaults to (not set) translated to the current application language. You can configure the yii\i18n\Formatter::nullDisplay property to set a custom placeholder. If you do not want special handling for null values, you can set yii\i18n\Formatter::nullDisplay to null.

Localizing Data Format

All output of the formatter is localized when the PHP intl extension is installed. You can configure the yii\i18n\Formatter::locale property of the formatter for this. If not configured, the application yii\base\Application::language is used as the locale. See the section on internationalization for more details. The Formatter will then choose the correct format for dates and numbers according to the locale including names of month and weekdays translated to the current language. Date formats are also affected by the yii\i18n\Formatter::timeZone which will also be taken from the application yii\base\Application::timeZone if not configured explicitly.

For example the date format call will output different results for different locales:

Yii::$app->formatter->locale = 'en-US';
echo Yii::$app->formatter->asDate('2014-01-01'); // output: January 1, 2014
Yii::$app->formatter->locale = 'de-DE';
echo Yii::$app->formatter->asDate('2014-01-01'); // output: 1. Januar 2014
Yii::$app->formatter->locale = 'ru-RU';
echo Yii::$app->formatter->asDate('2014-01-01'); // output: 1 января 2014 г.

Note that formatting may differ between different versions of the ICU library compiled with PHP and also based on the fact whether the PHP intl extension is installed or not. So to ensure your website works with the same output in all environments it is recommended to install the PHP intl extension in all environments and verify that the version of the ICU library is the same. See also: Setting up your PHP environment for internationalization.

Note also that even if the intl extension is installed, formatting date and time values for years >=2038 or <=1901 on 32bit systems will fall back to the PHP implementation, which does not provide localized month and day names, because intl uses a 32bit UNIX timestamp internally. On a 64bit system the intl formatter is used in all cases if installed.