Formatter
API reference › yii › i18n › Formatter
Formatter provides a set of commonly used data formatting methods.
The formatting methods provided by Formatter are all named in the form of asXyz().
The behavior of some of them may be configured via the properties of Formatter. For example,
by configuring $dateFormat, one may control how asDate() formats the value into a date string.
Formatter is configured as an application component in Application by default.
You can access that instance via Yii::$app->formatter.
The Formatter class is designed to format values according to a $locale. For this feature to work
the PHP intl extension has to be installed.
Most of the methods however work also if the PHP intl extension is not installed by providing
a fallback implementation. Without intl month and day names are in English only.
Note 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 because intl uses a 32bit UNIX timestamp internally.
On a 64bit system the intl formatter is used in all cases if installed.
Note: The Formatter class is meant to be used for formatting values for display to users in different languages and time zones. If you need to format a date or time in machine readable format, use the PHP date() function instead.
Properties
Section titled “Properties”| Property | Type | Description | Defined by |
|---|---|---|---|
$baseUnits | array | The base units that are used as multipliers for smallest possible unit from $measureUnits. Default: [self::UNIT_LENGTH => [self::UNIT_SYSTEM_IMPERIAL => 12,. Available since 2.0.13. | Formatter |
$behaviors read-only | array<yii\<static>> | List of behaviors attached to this component. | yii\ |
$booleanFormat | array | The text to be displayed when formatting a boolean value. Default: null. | Formatter |
$calendar | IntlCalendar| | The calendar to be used for date formatting. Default: null. Available since 2.0.7. | Formatter |
$currencyCode | string| | The 3-letter ISO 4217 currency code indicating the default currency to use for asCurrency(). Default: null. | Formatter |
$currencyDecimalSeparator | string| | The character displayed as the decimal point when formatting a currency. Default: null. Available since 2.0.35. | Formatter |
$dateFormat | string | The default format string to be used to format a date. Default: 'medium'. | Formatter |
$datetimeFormat | string | The default format string to be used to format a date and time. Default: 'medium'. | Formatter |
$decimalSeparator | string| | The character displayed as the decimal point when formatting a number. Default: null. | Formatter |
$defaultTimeZone | string | The time zone that is assumed for input values if they do not include a time zone explicitly. Default: 'UTC'. Available since 2.0.1. | Formatter |
$language | string| | The language code (e.g. en-US, en) that is used to translate internal messages. Default: null. Available since 2.0.28. | Formatter |
$locale | string| | The locale ID that is used to localize the date and number formatting. Default: null. | Formatter |
$measureUnits | array | Configuration of weight and length measurement units. Default: [self::UNIT_LENGTH => [self::UNIT_SYSTEM_IMPERIAL => ['inch' => 1,. Available since 2.0.13. | Formatter |
$nullDisplay | string| | The text to be displayed when formatting a null value. Default: null. | Formatter |
$numberFormatterOptions | array | A list of name value pairs that are passed to the intl NumberFormatter::setAttribute() method of all the number formatter objects created by createNumberFormatter(). Default: []. | Formatter |
$numberFormatterSymbols | array | A list of name value pairs that are passed to the intl NumberFormatter::setSymbol() method of all the number formatter objects created by createNumberFormatter(). Default: []. Available since 2.0.4. | Formatter |
$numberFormatterTextOptions | array | A list of name value pairs that are passed to the intl NumberFormatter::setTextAttribute() method of all the number formatter objects created by createNumberFormatter(). Default: []. | Formatter |
$sizeFormatBase | int | The base at which a kilobyte is calculated (1000 or 1024 bytes per kilobyte), used by asSize() and asShortSize(). Default: 1024. | Formatter |
$systemOfUnits | string | Default system of measure units. Default: self::UNIT_SYSTEM_METRIC. Available since 2.0.13. | Formatter |
$thousandSeparator | string| | The character displayed as the thousands separator (also called grouping separator) character when formatting a number. Default: null. | Formatter |
$timeFormat | string | The default format string to be used to format a time. Default: 'medium'. | Formatter |
$timeZone | string| | The time zone to use for formatting time and date values. Default: null. | Formatter |
Methods
Section titled “Methods”| Method | Description | Defined by |
|---|---|---|
__construct() | Constructor. | yii\ |
__call() | Calls the named method which is not a class method. | yii\ |
__clone() | This method is called after the object is created by cloning an existing one. | yii\ |
__get() | Returns the value of a component property. | yii\ |
__isset() | Checks if a property is set, i.e. defined and not null. | yii\ |
__set() | Sets the value of a component property. | yii\ |
__unset() | Sets a component property to be null. | yii\ |
asBoolean() | Formats the value as a boolean. | Formatter |
asCurrency() | Formats the value as a currency number. | Formatter |
asDate() | Formats the value as a date. | Formatter |
asDatetime() | Formats the value as a datetime. | Formatter |
asDecimal() | Formats the value as a decimal number. | Formatter |
asDuration() | Represents the value as duration in human readable format. | Formatter |
asEmail() | Formats the value as a mailto link. | Formatter |
asHtml() | Formats the value as HTML text. | Formatter |
asImage() | Formats the value as an image tag. | Formatter |
asInteger() | Formats the value as an integer number by removing any decimal digits without rounding. | Formatter |
asLength() | Formats the value as a length in human readable form for example 12 meters. | Formatter |
asNtext() | Formats the value as an HTML-encoded plain text with newlines converted into breaks. | Formatter |
asOrdinal() | Formats the value as a ordinal value of a number. | Formatter |
asParagraphs() | Formats the value as HTML-encoded text paragraphs. | Formatter |
asPercent() | Formats the value as a percent number with ”%” sign. | Formatter |
asRaw() | Formats the value as is without any formatting. | Formatter |
asRelativeTime() | Formats the value as the time interval between a date and now in human readable form. | Formatter |
asScientific() | Formats the value as a scientific number. | Formatter |
asShortLength() | Formats the value as a length in human readable form for example 12 m. | Formatter |
asShortSize() | Formats the value in bytes as a size in human readable form for example 12 kB. | Formatter |
asShortWeight() | Formats the value as a weight in human readable form for example 12 kg. | Formatter |
asSize() | Formats the value in bytes as a size in human readable form, for example 12 kilobytes. | Formatter |
asSpellout() | Formats the value as a number spellout. | Formatter |
asText() | Formats the value as an HTML-encoded plain text. | Formatter |
asTime() | Formats the value as a time. | Formatter |
asTimestamp() | Formats a date, time or datetime in a float number as UNIX timestamp (seconds since 01-01-1970). | Formatter |
asUrl() | Formats the value as a hyperlink. | Formatter |
asWeight() | Formats the value as a weight in human readable form for example 12 kilograms. | Formatter |
attachBehavior() | Attaches a behavior to this component. | yii\ |
attachBehaviors() | Attaches a list of behaviors to the component. | yii\ |
behaviors() | Returns a list of behaviors that this component should behave as. | yii\ |
canGetProperty() | Returns a value indicating whether a property can be read. | yii\ |
canSetProperty() | Returns a value indicating whether a property can be set. | yii\ |
className() static | Returns the fully qualified name of this class. | yii\ |
detachBehavior() | Detaches a behavior from the component. | yii\ |
detachBehaviors() | Detaches all behaviors from the component. | yii\ |
ensureBehaviors() | Makes sure that the behaviors declared in behaviors() are attached to this component. | yii\ |
format() | Formats the value based on the given format type. | Formatter |
getBehavior() | Returns the named behavior object. | yii\ |
getBehaviors() | Returns all behaviors attached to this component. | yii\ |
hasEventHandlers() | Returns a value indicating whether there is any handler attached to the named event. | yii\ |
hasMethod() | Returns a value indicating whether a method is defined. | yii\ |
hasProperty() | Returns a value indicating whether a property is defined for this component. | yii\ |
init() | Initializes the object. | Formatter |
off() | Detaches an existing event handler from this component. | yii\ |
on() | Attaches an event handler to an event. | yii\ |
trigger() | Triggers an event. | yii\ |
asCurrencyStringFallback() protected | Fallback for formatting value as a currency number. | Formatter |
asDecimalStringFallback() protected | Fallback for formatting value as a decimal number. | Formatter |
asIntegerStringFallback() protected | Fallback for formatting value as an integer number by removing any decimal digits without rounding. | Formatter |
asPercentStringFallback() protected | Fallback for formatting value as a percent number with ”%” sign. | Formatter |
createNumberFormatter() protected | Creates a number formatter based on the given type and format. | Formatter |
formatNumber() protected | Given the value in bytes formats number part of the human readable form. | Formatter |
isNormalizedValueMispresented() protected | Checks if string representations of given value and its normalized version are different. | Formatter |
normalizeDatetimeValue() protected | Normalizes the given datetime value as a DateTime object that can be taken by various date/time formatting methods. | Formatter |
normalizeNumericStringValue() protected | Normalizes a numeric string value. | Formatter |
normalizeNumericValue() protected | Normalizes a numeric input value. | Formatter |
Constants
Section titled “Constants”| Constant | Value | Description | Defined by |
|---|---|---|---|
UNIT_SYSTEM_METRIC | 'metric' | Available since 2.0.13. | Formatter |
UNIT_SYSTEM_IMPERIAL | 'imperial' | Available since 2.0.13. | Formatter |
FORMAT_WIDTH_LONG | 'long' | Available since 2.0.13. | Formatter |
FORMAT_WIDTH_SHORT | 'short' | Available since 2.0.13. | Formatter |
UNIT_LENGTH | 'length' | Available since 2.0.13. | Formatter |
UNIT_WEIGHT | 'mass' | Available since 2.0.13. | Formatter |
Property details
Section titled “Property details”$booleanFormat
Section titled “$booleanFormat ”public array $booleanFormat = nullThe text to be displayed when formatting a boolean value.
The first element corresponds
to the text displayed for false, the second element for true.
Defaults to ['No', 'Yes'], where Yes and No
will be translated according to $locale.
$calendar
Section titled “$calendar ”public IntlCalendar|int|null $calendar = nullThe calendar to be used for date formatting.
The value of this property will be directly
passed to the constructor of the IntlDateFormatter class.
Defaults to null, which means the Gregorian calendar will be used. You may also explicitly pass the constant
\IntlDateFormatter::GREGORIAN for Gregorian calendar.
To use an alternative calendar like for example the Jalali calendar,
set this property to \IntlDateFormatter::TRADITIONAL.
The calendar must then be specified in the $locale, for example for the persian calendar the configuration for the formatter would be:
'formatter' => [ 'locale' => 'fa_IR@calendar=persian', 'calendar' => \IntlDateFormatter::TRADITIONAL,],Available calendar names can be found in the ICU manual.
Since PHP 5.5 you may also use an instance of the IntlCalendar class.
Check the PHP manual for more details.
If the PHP intl extension is not available, setting this property will have no effect.
Since
2.0.7
$currencyCode
Section titled “$currencyCode ”public string|null $currencyCode = nullThe 3-letter ISO 4217 currency code indicating the default currency to use for asCurrency().
If not set, the currency code corresponding to $locale will be used.
Note that in this case the $locale has to be specified with a country code, e.g. en-US otherwise it
is not possible to determine the default currency.
$currencyDecimalSeparator
Section titled “$currencyDecimalSeparator ”public string|null $currencyDecimalSeparator = nullThe character displayed as the decimal point when formatting a currency.
If not set, the currency decimal separator corresponding to $locale will be used.
If PHP intl extension is not available, setting this property will have no effect.
Since
2.0.35
$dateFormat
Section titled “$dateFormat ”public string $dateFormat = 'medium'The default format string to be used to format a date.
This can be “short”, “medium”, “long”, or “full”, which represents a preset format of different lengths.
It can also be a custom format as specified in the ICU manual.
Alternatively this can be a string prefixed with php: representing a format that can be recognized by the
PHP date()-function.
For example:
'MM/dd/yyyy' // date in ICU format'php:m/d/Y' // the same date in PHP format$datetimeFormat
Section titled “$datetimeFormat ”public string $datetimeFormat = 'medium'The default format string to be used to format a date and time.
This can be “short”, “medium”, “long”, or “full”, which represents a preset format of different lengths.
It can also be a custom format as specified in the ICU manual.
Alternatively this can be a string prefixed with php: representing a format that can be recognized by the
PHP date() function.
For example:
'MM/dd/yyyy HH:mm:ss' // date and time in ICU format'php:m/d/Y H:i:s' // the same date and time in PHP format$decimalSeparator
Section titled “$decimalSeparator ”public string|null $decimalSeparator = nullThe character displayed as the decimal point when formatting a number.
If not set, the decimal separator corresponding to $locale will be used.
If PHP intl extension is not available, the default value is ’.’.
$defaultTimeZone
Section titled “$defaultTimeZone ”public string $defaultTimeZone = 'UTC'The time zone that is assumed for input values if they do not include a time zone explicitly.
The value must be a valid time zone identifier, e.g. UTC, Europe/Berlin or America/Chicago.
Please refer to the php manual for available time zones.
It defaults to UTC so you only have to adjust this value if you store datetime values in another time zone in your database.
Note that a UNIX timestamp is always in UTC by its definition. That means that specifying a default time zone different from UTC has no effect on date values given as UNIX timestamp.
Since
2.0.1
$language
Section titled “$language ”public string|null $language = nullThe language code (e.g. en-US, en) that is used to translate internal messages.
If not set, $locale will be used (without the @calendar param, if included).
Since
2.0.28
$locale
Section titled “$locale ”public string|null $locale = nullThe locale ID that is used to localize the date and number formatting.
For number and date formatting this is only effective when the
PHP intl extension is installed.
If not set, Application::$language will be used.
$measureUnits
Section titled “$measureUnits ”public array $measureUnits = [self::UNIT_LENGTH => [self::UNIT_SYSTEM_IMPERIAL => ['inch' => 1, 'foot' => 12, 'yard' => 36, 'chain' => 792, 'furlong' => 7920, 'mile' => 63360], self::UNIT_SYSTEM_METRIC => ['millimeter' => 1, 'centimeter' => 10, 'meter' => 1000, 'kilometer' => 1000000]], self::UNIT_WEIGHT => [self::UNIT_SYSTEM_IMPERIAL => ['grain' => 1, 'drachm' => 27.34375, 'ounce' => 437.5, 'pound' => 7000, 'stone' => 98000, 'quarter' => 196000, 'hundredweight' => 784000, 'ton' => 15680000], self::UNIT_SYSTEM_METRIC => ['gram' => 1, 'kilogram' => 1000, 'ton' => 1000000]]]Configuration of weight and length measurement units.
This array contains the most usable measurement units, but you can change it in case you have some special requirements.
For example, you can add smaller measure unit:
$this->measureUnits[self::UNIT_LENGTH][self::UNIT_SYSTEM_METRIC] = [ 'nanometer' => 0.000001]Since
2.0.13
$nullDisplay
Section titled “$nullDisplay ”public string|null $nullDisplay = nullThe text to be displayed when formatting a null value.
Defaults to '<span class="not-set">(not set)</span>', where (not set)
will be translated according to $locale.
$numberFormatterOptions
Section titled “$numberFormatterOptions ”public array $numberFormatterOptions = []A list of name value pairs that are passed to the intl NumberFormatter::setAttribute() method of all the number formatter objects created by createNumberFormatter().
This property takes only effect if the PHP intl extension is installed.
Please refer to the PHP manual for the possible options.
For example to adjust the maximum and minimum value of fraction digits you can configure this property like the following:
[ NumberFormatter::MIN_FRACTION_DIGITS => 0, NumberFormatter::MAX_FRACTION_DIGITS => 2,]$numberFormatterSymbols
Section titled “$numberFormatterSymbols ”public array $numberFormatterSymbols = []A list of name value pairs that are passed to the intl NumberFormatter::setSymbol() method of all the number formatter objects created by createNumberFormatter().
This property takes only effect if the PHP intl extension is installed.
Please refer to the PHP manual for the possible options.
For example to choose a custom currency symbol, e.g. U+20BD instead of руб. for Russian Ruble:
[ NumberFormatter::CURRENCY_SYMBOL => '₽',]Since
2.0.4
$numberFormatterTextOptions
Section titled “$numberFormatterTextOptions ”public array $numberFormatterTextOptions = []A list of name value pairs that are passed to the intl NumberFormatter::setTextAttribute() method of all the number formatter objects created by createNumberFormatter().
This property takes only effect if the PHP intl extension is installed.
Please refer to the PHP manual for the possible options.
For example to change the minus sign for negative numbers you can configure this property like the following:
[ NumberFormatter::NEGATIVE_PREFIX => 'MINUS',]$sizeFormatBase
Section titled “$sizeFormatBase ”public int $sizeFormatBase = 1024The base at which a kilobyte is calculated (1000 or 1024 bytes per kilobyte), used by asSize() and asShortSize().
Defaults to 1024.
$systemOfUnits
Section titled “$systemOfUnits ”public string $systemOfUnits = self::UNIT_SYSTEM_METRICDefault system of measure units.
Defaults to UNIT_SYSTEM_METRIC.
Possible values:
Since
2.0.13
$thousandSeparator
Section titled “$thousandSeparator ”public string|null $thousandSeparator = nullThe character displayed as the thousands separator (also called grouping separator) character when formatting a number.
If not set, the thousand separator corresponding to $locale will be used.
If PHP intl extension is not available, the default value is ’,’.
$timeFormat
Section titled “$timeFormat ”public string $timeFormat = 'medium'The default format string to be used to format a time.
This can be “short”, “medium”, “long”, or “full”, which represents a preset format of different lengths.
It can also be a custom format as specified in the ICU manual.
Alternatively this can be a string prefixed with php: representing a format that can be recognized by the
PHP date()-function.
For example:
'HH:mm:ss' // time in ICU format'php:H:i:s' // the same time in PHP format$timeZone
Section titled “$timeZone ”public string|null $timeZone = nullThe time zone to use for formatting time and date values.
This can be any value that may be passed to date_default_timezone_set()
e.g. UTC, Europe/Berlin or America/Chicago.
Refer to the php manual for available time zones.
If this property is not set, Application::$timeZone will be used.
Note that the default time zone for input data is assumed to be UTC by default if no time zone is included in the input date value.
If you store your data in a different time zone in the database, you have to adjust $defaultTimeZone accordingly.
Method details
Section titled “Method details”asBoolean()
Section titled “asBoolean() ”public function asBoolean(mixed $value): stringFormats the value as a boolean.
Parameters
| Parameter | Type | Description |
|---|---|---|
$value | mixed | The value to be formatted. |
Returns
string: The formatted result.
See also
asCurrency()
Section titled “asCurrency() ”public function asCurrency(mixed $value, string|null $currency = null, array $options = [], array $textOptions = []): stringFormats the value as a currency number.
This function does not require the PHP intl extension to be installed to work, but it is highly recommended to install it to get good formatting results.
Since 2.0.16 numbers that are mispresented after normalization are formatted as strings using fallback function without PHP intl extension support. For very big numbers it’s recommended to pass them as strings and not use scientific notation otherwise the output might be wrong.
Parameters
| Parameter | Type | Description |
|---|---|---|
$value | mixed | The value to be formatted. |
$currency | string| | The 3-letter ISO 4217 currency code indicating the currency to use. If null, $currencyCode will be used. |
$options | array | Optional configuration for the number formatter. This parameter will be merged with $numberFormatterOptions. |
$textOptions | array | Optional configuration for the number formatter. This parameter will be merged with $numberFormatterTextOptions. |
Returns
string: The formatted result.
Throws
yii\base\InvalidArgumentException: if the input value is not numeric or the formatting failed.yii\base\InvalidConfigException: if no currency is given and$currencyCodeis not defined.
asDate()
Section titled “asDate() ”public function asDate(int|string|DateTime|DateTimeInterface|null $value, string|null $format = null): stringFormats the value as a date.
Parameters
| Parameter | Type | Description |
|---|---|---|
$value | int|DateTime|DateTimeInterface| | The value to be formatted. The following types of value are supported: - an integer representing a UNIX timestamp. A UNIX timestamp is always in UTC by its definition. - a string that can be parsed to create a DateTime object. The timestamp is assumed to be in $defaultTimeZone unless a time zone is explicitly given. - a PHP DateTime object. You may set the time zone for the DateTime object to specify the source time zone. The formatter will convert date values according to $timeZone before formatting it. If no timezone conversion should be performed, you need to set $defaultTimeZone and $timeZone to the same value. Also no conversion will be performed on values that have no time information, e.g. "2017-06-05". |
$format | string| | The format used to convert the value into a date string. If null, $dateFormat will be used. This can be “short”, “medium”, “long”, or “full”, which represents a preset format of different lengths. It can also be a custom format as specified in the ICU manual. Alternatively this can be a string prefixed with php: representing a format that can be recognized by the PHP date()-function. |
Returns
string: The formatted result.
Throws
yii\base\InvalidArgumentException: if the input value can not be evaluated as a date value.yii\base\InvalidConfigException: if the date format is invalid.
See also
asDatetime()
Section titled “asDatetime() ”public function asDatetime(int|string|DateTime|DateTimeInterface|null $value, string|null $format = null): stringFormats the value as a datetime.
Parameters
| Parameter | Type | Description |
|---|---|---|
$value | int|DateTime|DateTimeInterface| | The value to be formatted. The following types of value are supported: - an integer representing a UNIX timestamp. A UNIX timestamp is always in UTC by its definition. - a string that can be parsed to create a DateTime object. The timestamp is assumed to be in $defaultTimeZone unless a time zone is explicitly given. - a PHP DateTime object. You may set the time zone for the DateTime object to specify the source time zone. The formatter will convert date values according to $timeZone before formatting it. If no timezone conversion should be performed, you need to set $defaultTimeZone and $timeZone to the same value. |
$format | string| | The format used to convert the value into a date string. If null, $datetimeFormat will be used. This can be “short”, “medium”, “long”, or “full”, which represents a preset format of different lengths. It can also be a custom format as specified in the ICU manual. Alternatively this can be a string prefixed with php: representing a format that can be recognized by the PHP date()-function. |
Returns
string: The formatted result.
Throws
yii\base\InvalidArgumentException: if the input value can not be evaluated as a date value.yii\base\InvalidConfigException: if the date format is invalid.
See also
asDecimal()
Section titled “asDecimal() ”public function asDecimal(mixed $value, int|null $decimals = null, array $options = [], array $textOptions = []): stringFormats the value as a decimal number.
Property $decimalSeparator will be used to represent the decimal point. The
value is rounded automatically to the defined decimal digits.
Since 2.0.16 numbers that are mispresented after normalization are formatted as strings using fallback function without PHP intl extension support. For very big numbers it’s recommended to pass them as strings and not use scientific notation otherwise the output might be wrong.
Parameters
| Parameter | Type | Description |
|---|---|---|
$value | mixed | The value to be formatted. |
$decimals | int| | The number of digits after the decimal point. If not given, the number of digits depends in the input value and is determined based on NumberFormatter::MIN_FRACTION_DIGITS and NumberFormatter::MAX_FRACTION_DIGITS, which can be configured using $numberFormatterOptions. If the PHP intl extension is not available, the default value is 2. If you want consistent behavior between environments where intl is available and not, you should explicitly specify a value here. |
$options | array | Optional configuration for the number formatter. This parameter will be merged with $numberFormatterOptions. |
$textOptions | array | Optional configuration for the number formatter. This parameter will be merged with $numberFormatterTextOptions. |
Returns
string: The formatted result.
Throws
yii\base\InvalidArgumentException: if the input value is not numeric or the formatting failed.
See also
asDuration()
Section titled “asDuration() ”public function asDuration(DateInterval|string|int|null $value, string $implodeString = ', ', string $negativeSign = '-'): stringRepresents the value as duration in human readable format.
Parameters
| Parameter | Type | Description |
|---|---|---|
$value | DateInterval| | The value to be formatted. Acceptable formats: - DateInterval object - integer - number of seconds. For example: value 131 represents 2 minutes, - ISO8601 duration format. For example, all of these values represent 1 day, duration: 2015-01-01T13:00:00Z/2015-01-02T13:30:00Z - between two datetime values 2015-01-01T13:00:00Z/P1D2H30M - time interval after datetime value P1D2H30M/2015-01-02T13:30:00Z - time interval before datetime value P1D2H30M - simply a date interval P-1D2H30M - a negative date interval (-1 day,) |
$implodeString | string | Will be used to concatenate duration parts. Defaults to ,. |
$negativeSign | string | Will be prefixed to the formatted duration, when it is negative. Defaults to -. |
Returns
string: The formatted duration.
Since
2.0.7
asEmail()
Section titled “asEmail() ”public function asEmail(string|null $value, array $options = []): stringFormats the value as a mailto link.
Parameters
| Parameter | Type | Description |
|---|---|---|
$value | string| | The value to be formatted. |
$options | array | The tag options in terms of name-value pairs. See Html::mailto(). |
Returns
string: The formatted result.
asHtml()
Section titled “asHtml() ”public function asHtml(string|null $value, array|null $config = null): stringFormats the value as HTML text.
The value will be purified using HtmlPurifier to avoid XSS attacks.
Use asRaw() if you do not want any purification of the value.
Parameters
| Parameter | Type | Description |
|---|---|---|
$value | string| | The value to be formatted. |
$config | array| | The configuration for the HTMLPurifier class. |
Returns
string: The formatted result.
asImage()
Section titled “asImage() ”public function asImage(mixed $value, array $options = []): stringFormats the value as an image tag.
Parameters
| Parameter | Type | Description |
|---|---|---|
$value | mixed | The value to be formatted. |
$options | array | The tag options in terms of name-value pairs. See Html::img(). |
Returns
string: The formatted result.
asInteger()
Section titled “asInteger() ”public function asInteger(mixed $value, array $options = [], array $textOptions = []): stringFormats the value as an integer number by removing any decimal digits without rounding.
Since 2.0.16 numbers that are mispresented after normalization are formatted as strings using fallback function without PHP intl extension support. For very big numbers it’s recommended to pass them as strings and not use scientific notation otherwise the output might be wrong.
Parameters
| Parameter | Type | Description |
|---|---|---|
$value | mixed | The value to be formatted. |
$options | array | Optional configuration for the number formatter. This parameter will be merged with $numberFormatterOptions. |
$textOptions | array | Optional configuration for the number formatter. This parameter will be merged with $numberFormatterTextOptions. |
Returns
string: The formatted result.
Throws
yii\base\InvalidArgumentException: if the input value is not numeric or the formatting failed.
asLength()
Section titled “asLength() ”public function asLength(float|int $value, int|null $decimals = null, array $numberOptions = [], array $textOptions = []): stringFormats the value as a length in human readable form for example 12 meters.
Check properties $baseUnits if you need to change unit of value as the multiplier
of the smallest unit and $systemOfUnits to switch between UNIT_SYSTEM_METRIC or UNIT_SYSTEM_IMPERIAL.
Parameters
| Parameter | Type | Description |
|---|---|---|
$value | float| | Value to be formatted. |
$decimals | int| | The number of digits after the decimal point. |
$numberOptions | array | Optional configuration for the number formatter. This parameter will be merged with $numberFormatterOptions. |
$textOptions | array | Optional configuration for the number formatter. This parameter will be merged with $numberFormatterTextOptions. |
Returns
string: The formatted result.
Throws
yii\base\InvalidArgumentException: if the input value is not numeric or the formatting failed.yii\base\InvalidConfigException: when INTL is not installed or does not contain required information.
Since
2.0.13
See also
asNtext()
Section titled “asNtext() ”public function asNtext(string|null $value): stringFormats the value as an HTML-encoded plain text with newlines converted into breaks.
Parameters
| Parameter | Type | Description |
|---|---|---|
$value | string| | The value to be formatted. |
Returns
string: The formatted result.
asOrdinal()
Section titled “asOrdinal() ”public function asOrdinal(mixed $value): stringFormats the value as a ordinal value of a number.
This function requires the PHP intl extension to be installed.
This formatter does not work well with very big numbers.
Parameters
| Parameter | Type | Description |
|---|---|---|
$value | mixed | The value to be formatted |
Returns
string: The formatted result.
Throws
yii\base\InvalidArgumentException: if the input value is not numeric or the formatting failed.yii\base\InvalidConfigException: when the PHP intl extension is not available.
asParagraphs()
Section titled “asParagraphs() ”public function asParagraphs(string|null $value): stringFormats the value as HTML-encoded text paragraphs.
Each text paragraph is enclosed within a <p> tag.
One or multiple consecutive empty lines divide two paragraphs.
Parameters
| Parameter | Type | Description |
|---|---|---|
$value | string| | The value to be formatted. |
Returns
string: The formatted result.
asPercent()
Section titled “asPercent() ”public function asPercent(mixed $value, int|null $decimals = null, array $options = [], array $textOptions = []): stringFormats the value as a percent number with ”%” sign.
Since 2.0.16 numbers that are mispresented after normalization are formatted as strings using fallback function without PHP intl extension support. For very big numbers it’s recommended to pass them as strings and not use scientific notation otherwise the output might be wrong.
Parameters
| Parameter | Type | Description |
|---|---|---|
$value | mixed | The value to be formatted. It must be a factor e.g. 0.75 will result in 75%. |
$decimals | int| | The number of digits after the decimal point. If not given, the number of digits depends in the input value and is determined based on NumberFormatter::MIN_FRACTION_DIGITS and NumberFormatter::MAX_FRACTION_DIGITS, which can be configured using $numberFormatterOptions. If the PHP intl extension is not available, the default value is 0. If you want consistent behavior between environments where intl is available and not, you should explicitly specify a value here. |
$options | array | Optional configuration for the number formatter. This parameter will be merged with $numberFormatterOptions. |
$textOptions | array | Optional configuration for the number formatter. This parameter will be merged with $numberFormatterTextOptions. |
Returns
string: The formatted result.
Throws
yii\base\InvalidArgumentException: if the input value is not numeric or the formatting failed.
asRaw()
Section titled “asRaw() ”public function asRaw(mixed $value): stringFormats the value as is without any formatting.
This method simply returns back the parameter without any format.
The only exception is a null value which will be formatted using $nullDisplay.
Parameters
| Parameter | Type | Description |
|---|---|---|
$value | mixed | The value to be formatted. |
Returns
string: The formatted result.
asRelativeTime()
Section titled “asRelativeTime() ”public function asRelativeTime(int|string|DateTime|DateTimeInterface|DateInterval|null $value, int|string|DateTime|DateTimeInterface|null $referenceTime = null): stringFormats the value as the time interval between a date and now in human readable form.
This method can be used in three different ways:
- Using a timestamp that is relative to
now. - Using a timestamp that is relative to the
$referenceTime. - Using a
DateIntervalobject.
Parameters
| Parameter | Type | Description |
|---|---|---|
$value | int|DateTime|DateTimeInterface|DateInterval| | The value to be formatted. The following types of value are supported: - an integer representing a UNIX timestamp - a string that can be parsed to create a DateTime object. The timestamp is assumed to be in $defaultTimeZone unless a time zone is explicitly given. - a PHP DateTime object - a PHP DateInterval object (a positive time interval will refer to the past, a negative one to the future) |
$referenceTime | int|DateTime|DateTimeInterface| | If specified the value is used as a reference time instead of now when $value is not a DateInterval object. |
Returns
string: The formatted result.
Throws
yii\base\InvalidArgumentException: if the input value can not be evaluated as a date value.
asScientific()
Section titled “asScientific() ”public function asScientific(mixed $value, int|null $decimals = null, array $options = [], array $textOptions = []): stringFormats the value as a scientific number.
Parameters
| Parameter | Type | Description |
|---|---|---|
$value | mixed | The value to be formatted. |
$decimals | int| | The number of digits after the decimal point. If not given, the number of digits depends in the input value and is determined based on NumberFormatter::MIN_FRACTION_DIGITS and NumberFormatter::MAX_FRACTION_DIGITS, which can be configured using $numberFormatterOptions. If the PHP intl extension is not available, the default value depends on your PHP configuration. If you want consistent behavior between environments where intl is available and not, you should explicitly specify a value here. |
$options | array | Optional configuration for the number formatter. This parameter will be merged with $numberFormatterOptions. |
$textOptions | array | Optional configuration for the number formatter. This parameter will be merged with $numberFormatterTextOptions. |
Returns
string: The formatted result.
Throws
yii\base\InvalidArgumentException: if the input value is not numeric or the formatting failed.
asShortLength()
Section titled “asShortLength() ”public function asShortLength(float|int $value, int|null $decimals = null, array $options = [], array $textOptions = []): stringFormats the value as a length in human readable form for example 12 m.
This is the short form of asLength().
Check properties $baseUnits if you need to change unit of value as the multiplier
of the smallest unit and $systemOfUnits to switch between UNIT_SYSTEM_METRIC or UNIT_SYSTEM_IMPERIAL.
Parameters
| Parameter | Type | Description |
|---|---|---|
$value | float| | Value to be formatted. |
$decimals | int| | The number of digits after the decimal point. |
$options | array | Optional configuration for the number formatter. This parameter will be merged with $numberFormatterOptions. |
$textOptions | array | Optional configuration for the number formatter. This parameter will be merged with $numberFormatterTextOptions. |
Returns
string: The formatted result.
Throws
yii\base\InvalidArgumentException: if the input value is not numeric or the formatting failed.yii\base\InvalidConfigException: when INTL is not installed or does not contain required information.
Since
2.0.13
See also
asShortSize()
Section titled “asShortSize() ”public function asShortSize(string|int|float|null $value, int|null $decimals = null, array $options = [], array $textOptions = []): stringFormats the value in bytes as a size in human readable form for example 12 kB.
This is the short form of asSize().
If $sizeFormatBase is 1024, binary prefixes (e.g. kibibyte/KiB, mebibyte/MiB, …)
are used in the formatting result.
Parameters
| Parameter | Type | Description |
|---|---|---|
$value | string| | Value in bytes to be formatted. |
$decimals | int| | The number of digits after the decimal point. |
$options | array | Optional configuration for the number formatter. This parameter will be merged with $numberFormatterOptions. |
$textOptions | array | Optional configuration for the number formatter. This parameter will be merged with $numberFormatterTextOptions. |
Returns
string: The formatted result.
Throws
yii\base\InvalidArgumentException: if the input value is not numeric or the formatting failed.
See also
asShortWeight()
Section titled “asShortWeight() ”public function asShortWeight(float|int $value, int|null $decimals = null, array $options = [], array $textOptions = []): stringFormats the value as a weight in human readable form for example 12 kg.
This is the short form of asWeight().
Check properties $baseUnits if you need to change unit of value as the multiplier
of the smallest unit and $systemOfUnits to switch between UNIT_SYSTEM_METRIC or UNIT_SYSTEM_IMPERIAL.
Parameters
| Parameter | Type | Description |
|---|---|---|
$value | float| | Value to be formatted. |
$decimals | int| | The number of digits after the decimal point. |
$options | array | Optional configuration for the number formatter. This parameter will be merged with $numberFormatterOptions. |
$textOptions | array | Optional configuration for the number formatter. This parameter will be merged with $numberFormatterTextOptions. |
Returns
string: The formatted result.
Throws
yii\base\InvalidArgumentException: if the input value is not numeric or the formatting failed.yii\base\InvalidConfigException: when INTL is not installed or does not contain required information.
Since
2.0.13
asSize()
Section titled “asSize() ”public function asSize(string|int|float|null $value, int|null $decimals = null, array $options = [], array $textOptions = []): stringFormats the value in bytes as a size in human readable form, for example 12 kilobytes.
If $sizeFormatBase is 1024, binary prefixes (e.g. kibibyte/KiB, mebibyte/MiB, …)
are used in the formatting result.
Parameters
| Parameter | Type | Description |
|---|---|---|
$value | string| | Value in bytes to be formatted. |
$decimals | int| | The number of digits after the decimal point. |
$options | array | Optional configuration for the number formatter. This parameter will be merged with $numberFormatterOptions. |
$textOptions | array | Optional configuration for the number formatter. This parameter will be merged with $numberFormatterTextOptions. |
Returns
string: The formatted result.
Throws
yii\base\InvalidArgumentException: if the input value is not numeric or the formatting failed.
See also
asSpellout()
Section titled “asSpellout() ”public function asSpellout(mixed $value): stringFormats the value as a number spellout.
This function requires the PHP intl extension to be installed.
This formatter does not work well with very big numbers.
Parameters
| Parameter | Type | Description |
|---|---|---|
$value | mixed | The value to be formatted |
Returns
string: The formatted result.
Throws
yii\base\InvalidArgumentException: if the input value is not numeric or the formatting failed.yii\base\InvalidConfigException: when the PHP intl extension is not available.
asText()
Section titled “asText() ”public function asText(string|null $value): stringFormats the value as an HTML-encoded plain text.
Parameters
| Parameter | Type | Description |
|---|---|---|
$value | string| | The value to be formatted. |
Returns
string: The formatted result.
asTime()
Section titled “asTime() ”public function asTime(int|string|DateTime|DateTimeInterface|null $value, string|null $format = null): stringFormats the value as a time.
Parameters
| Parameter | Type | Description |
|---|---|---|
$value | int|DateTime|DateTimeInterface| | The value to be formatted. The following types of value are supported: - an integer representing a UNIX timestamp. A UNIX timestamp is always in UTC by its definition. - a string that can be parsed to create a DateTime object. The timestamp is assumed to be in $defaultTimeZone unless a time zone is explicitly given. - a PHP DateTime object. You may set the time zone for the DateTime object to specify the source time zone. The formatter will convert date values according to $timeZone before formatting it. If no timezone conversion should be performed, you need to set $defaultTimeZone and $timeZone to the same value. |
$format | string| | The format used to convert the value into a date string. If null, $timeFormat will be used. This can be “short”, “medium”, “long”, or “full”, which represents a preset format of different lengths. It can also be a custom format as specified in the ICU manual. Alternatively this can be a string prefixed with php: representing a format that can be recognized by the PHP date()-function. |
Returns
string: The formatted result.
Throws
yii\base\InvalidArgumentException: if the input value can not be evaluated as a date value.yii\base\InvalidConfigException: if the date format is invalid.
See also
asTimestamp()
Section titled “asTimestamp() ”public function asTimestamp(int|string|DateTime|DateTimeInterface|null $value): stringFormats a date, time or datetime in a float number as UNIX timestamp (seconds since 01-01-1970).
Parameters
| Parameter | Type | Description |
|---|---|---|
$value | int|DateTime|DateTimeInterface| | The value to be formatted. The following types of value are supported: - an integer representing a UNIX timestamp - a string that can be parsed to create a DateTime object. The timestamp is assumed to be in $defaultTimeZone unless a time zone is explicitly given. - a PHP DateTime object |
Returns
string: The formatted result.
asUrl()
Section titled “asUrl() ”public function asUrl(mixed $value, array $options = []): stringFormats the value as a hyperlink.
Parameters
| Parameter | Type | Description |
|---|---|---|
$value | mixed | The value to be formatted. |
$options | array | The tag options in terms of name-value pairs. See Html::a(). Since 2.0.43 there is a special option available scheme - if set it won’t be passed to Html::a() but it will control the URL protocol part of the link by normalizing URL and ensuring that it uses specified scheme. See Url::ensureScheme(). If scheme is not set the original behavior is preserved which is to add “http://” prefix when ”://” string is not found in the $value. |
Returns
string: The formatted result.
asWeight()
Section titled “asWeight() ”public function asWeight(float|int $value, int|null $decimals = null, array $options = [], array $textOptions = []): stringFormats the value as a weight in human readable form for example 12 kilograms.
Check properties $baseUnits if you need to change unit of value as the multiplier
of the smallest unit and $systemOfUnits to switch between UNIT_SYSTEM_METRIC or UNIT_SYSTEM_IMPERIAL.
Parameters
| Parameter | Type | Description |
|---|---|---|
$value | float| | Value to be formatted. |
$decimals | int| | The number of digits after the decimal point. |
$options | array | Optional configuration for the number formatter. This parameter will be merged with $numberFormatterOptions. |
$textOptions | array | Optional configuration for the number formatter. This parameter will be merged with $numberFormatterTextOptions. |
Returns
string: The formatted result.
Throws
yii\base\InvalidArgumentException: if the input value is not numeric or the formatting failed.yii\base\InvalidConfigException: when INTL is not installed or does not contain required information.
Since
2.0.13
format()
Section titled “format() ”public function format(mixed $value, string|array|Closure $format): stringFormats the value based on the given format type.
This method will call one of the “as” methods available in this class to do the formatting.
For type “xyz”, the method “asXyz” will be used. For example, if the format is “html”,
then asHtml() will be used. Format names are case insensitive.
Parameters
| Parameter | Type | Description |
|---|---|---|
$value | mixed | The value to be formatted. |
$format | string|Closure | The format of the value, e.g., “html”, “text” or an anonymous function returning the formatted value. To specify additional parameters of the formatting method, you may use an array. The first element of the array specifies the format name, while the rest of the elements will be used as the parameters to the formatting method. For example, a format of ['date', will cause the invocation of asDate($value,. The anonymous function signature should be: function($value,, where $value is the value that should be formatted and $formatter is an instance of the Formatter class, which can be used to call other formatting functions. The possibility to use an anonymous function is available since version 2.0.13. |
Returns
string: The formatting result.
Throws
yii\base\InvalidArgumentException: if the format type is not supported by this class.
init()
Section titled “init() ”public function init(): mixedInitializes the object.
This method is invoked at the end of the constructor after the object is initialized with the given configuration.
Returns
mixed
asCurrencyStringFallback()
Section titled “asCurrencyStringFallback() ”protected function asCurrencyStringFallback(string|int|float $value, string|null $currency = null): stringFallback for formatting value as a currency number.
Parameters
| Parameter | Type | Description |
|---|---|---|
$value | string| | The value to be formatted. |
$currency | string| | The 3-letter ISO 4217 currency code indicating the currency to use. If null, $currencyCode will be used. |
Returns
string: The formatted result.
Throws
yii\base\InvalidConfigException: if no currency is given and$currencyCodeis not defined.
Since
2.0.16
asDecimalStringFallback()
Section titled “asDecimalStringFallback() ”protected function asDecimalStringFallback(string|int|float $value, int|null $decimals = 2): stringFallback for formatting value as a decimal number.
Property $decimalSeparator will be used to represent the decimal point. The value is rounded automatically
to the defined decimal digits.
Parameters
| Parameter | Type | Description |
|---|---|---|
$value | string| | The value to be formatted. |
$decimals | int| | The number of digits after the decimal point. The default value is 2. |
Returns
string: The formatted result.
Since
2.0.16
See also
asIntegerStringFallback()
Section titled “asIntegerStringFallback() ”protected function asIntegerStringFallback(string|int|float $value): stringFallback for formatting value as an integer number by removing any decimal digits without rounding.
Parameters
| Parameter | Type | Description |
|---|---|---|
$value | string| | The value to be formatted. |
Returns
string: The formatted result.
Since
2.0.16
asPercentStringFallback()
Section titled “asPercentStringFallback() ”protected function asPercentStringFallback(string|int|float $value, int|null $decimals = null): stringFallback for formatting value as a percent number with ”%” sign.
Property $decimalSeparator will be used to represent the decimal point. The value is rounded automatically
to the defined decimal digits.
Parameters
| Parameter | Type | Description |
|---|---|---|
$value | string| | The value to be formatted. |
$decimals | int| | The number of digits after the decimal point. The default value is 0. |
Returns
string: The formatted result.
Since
2.0.16
createNumberFormatter()
Section titled “createNumberFormatter() ”protected function createNumberFormatter(int $style, int|null $decimals = null, array $options = [], array $textOptions = []): NumberFormatterCreates a number formatter based on the given type and format.
You may override this method to create a number formatter based on patterns.
Parameters
| Parameter | Type | Description |
|---|---|---|
$style | int | The type of the number formatter. Values: NumberFormatter::DECIMAL, ::CURRENCY, ::PERCENT, ::SCIENTIFIC, ::SPELLOUT, ::ORDINAL ::DURATION, ::PATTERN_RULEBASED, ::DEFAULT_STYLE, ::IGNORE |
$decimals | int| | The number of digits after the decimal point. |
$options | array | Optional configuration for the number formatter. This parameter will be merged with $numberFormatterOptions. |
$textOptions | array | Optional configuration for the number formatter. This parameter will be merged with $numberFormatterTextOptions. |
Returns
NumberFormatter: The created formatter instance
formatNumber()
Section titled “formatNumber() ”protected function formatNumber(string|int|float $value, int|null $decimals, int $maxPosition, array|int $formatBase, array $options, array $textOptions): arrayGiven the value in bytes formats number part of the human readable form.
Parameters
| Parameter | Type | Description |
|---|---|---|
$value | string| | Value in bytes to be formatted. |
$decimals | int| | The number of digits after the decimal point |
$maxPosition | int | Maximum internal position of size unit, ignored if $formatBase is an array |
$formatBase | array| | The base at which each next unit is calculated, either 1000 or 1024, or an array |
$options | array | Optional configuration for the number formatter. This parameter will be merged with $numberFormatterOptions. |
$textOptions | array | Optional configuration for the number formatter. This parameter will be merged with $numberFormatterTextOptions. |
Returns
array: [parameters for Yii::t containing formatted number, internal position of size unit]
Throws
yii\base\InvalidArgumentException: if the input value is not numeric or the formatting failed.
Since
2.0.32
isNormalizedValueMispresented()
Section titled “isNormalizedValueMispresented() ”protected function isNormalizedValueMispresented(string|float|int $value, float|int $normalizedValue): boolChecks if string representations of given value and its normalized version are different.
Parameters
| Parameter | Type | Description |
|---|---|---|
$value | string| | |
$normalizedValue | float| |
Returns
bool
Since
2.0.16
normalizeDatetimeValue()
Section titled “normalizeDatetimeValue() ”protected function normalizeDatetimeValue(int|string|DateTime|DateTimeInterface|null $value, bool $checkDateTimeInfo = false): DateTime|arrayNormalizes the given datetime value as a DateTime object that can be taken by various date/time formatting methods.
Parameters
| Parameter | Type | Description |
|---|---|---|
$value | int|DateTime|DateTimeInterface| | The datetime value to be normalized. The following types of value are supported: - an integer representing a UNIX timestamp - a string that can be parsed to create a DateTime object. The timestamp is assumed to be in $defaultTimeZone unless a time zone is explicitly given. - a PHP DateTime object |
$checkDateTimeInfo | bool | Whether to also check if the date/time value has some time and date information attached. Defaults to false. If true, the method will then return an array with the first element being the normalized timestamp, the second a boolean indicating whether the timestamp has time information and third a boolean indicating whether the timestamp has date information. This parameter is available since version 2.0.1. |
Returns
DateTime|array: The normalized datetime value Since version 2.0.1 this may also return an array if $checkDateTimeInfo is true. The first element of the array is the normalized timestamp and the second is a boolean indicating whether the timestamp has time information or it is just a date value. Since version 2.0.12 the array has third boolean element indicating whether the timestamp has date information or it is just a time value.
Throws
yii\base\InvalidArgumentException: if the input value can not be evaluated as a date value.
normalizeNumericStringValue()
Section titled “normalizeNumericStringValue() ”protected function normalizeNumericStringValue(string $value): stringNormalizes a numeric string value.
Parameters
| Parameter | Type | Description |
|---|---|---|
$value | string |
Returns
string: The normalized number value as a string
Since
2.0.16
normalizeNumericValue()
Section titled “normalizeNumericValue() ”protected function normalizeNumericValue(mixed $value): float|intNormalizes a numeric input value.
- everything empty will result in
0 - a numeric string will be casted to float
- everything else will be returned if it is numeric, otherwise an exception is thrown.
Parameters
| Parameter | Type | Description |
|---|---|---|
$value | mixed | The input value |
Returns
float|int: The normalized number value
Throws
yii\base\InvalidArgumentException: if the input value is not numeric.