yii\i18n\Formatter is a small formatting assistant, which is very helpful for us to achieve user-friendly display on the front end.
1. Commonly used attributes
(1)$dateFormat
Date format: yyyy-MM-dd, or "short", "medium ", "long", or "full"
(2)$datetimeFormat
Specific time format: yyyy-MM-dd HH:mm:ss
(3) $locale
Regional location, if not set, yii\base\Application::$language will be used, and the format will be displayed according to the customary display format of this region
(4)$defaultTimeZone
Time zone, default UTC
To use formatter, you need to configure it in config:
'formatter' => [ 'dateFormat' => 'yyyy-MM-dd', 'datetimeFormat' => 'yyyy-MM-dd HH:mm:ss', 'decimalSeparator' => ',', 'thousandSeparator' => ' ', 'currencyCode' => 'CNY', ],
2. Formatting
echo Yii::$app->formatter->asRelativeTime(1463632983).'<br/>'; // 几天前 几小时前 echo Yii::$app->formatter->asDatetime(1463606983).'<br>'; // 2015-6-16 11:51:43 echo Yii::$app->formatter->asDatetime('now').'<br>'; // 也可处理null值的输出显示: echo Yii::$app->formatter->asDate(null).'<br>'; // 输出: (未设置) echo Yii::$app->formatter->asPercent(0.125, 2).'<br>'; // 输出: 12.50% echo Yii::$app->formatter->asTimestamp('now').'<br>';//输出时间戳 echo Yii::$app->formatter->asTime(1412599260).'<br>'; // 14:41:00 echo Yii::$app->formatter->asTime('2014-10-06 12:41:00').'<br>'; // 14:41:00 echo Yii::$app->formatter->asTime('2014-10-06 14:41:00 CEST').'<br>'; // 14:41:00 echo Yii::$app->formatter->asRaw(1463606983).'<br>';//简单输出输入值 echo Yii::$app->formatter->asText('<h3>hello</h3>').'<br>';//将字符串中html标签当做字符串输出 echo Yii::$app->formatter->asHtml('<h3>hello</h3>').'<br>';//作为Html的文档输出 echo Yii::$app->formatter->asNtext("<h3>hello.\nword</h3>").'<br>';//在字符串中遇到\n可以将它作为换行符实现 echo Yii::$app->formatter->asEmail('cebe@example.com').'<br>';// 输出: <a href="mailto:cebe@example.com"> cebe@example.com</a> echo Yii::$app->formatter->asParagraphs('hello').'<br>';// 值会转换成HTML编码的文本段落,用<p>标签包裹; echo Yii::$app->formatter->asUrl('www.baidu.com').'<br>';//值会格式化成url的连接 echo Yii::$app->formatter->asImage('my2.jpeg',['alt'=>'图片无法显示']).'<br>';//图片的链接会转化成<img src= 'my.jpg'/> echo Yii::$app->formatter->asBoolean(true).'<br>';//输出yes
PHP Chinese website, There are a large number of free Yii introductory tutorials, everyone is welcome to learn!
The above is the detailed content of How to format data in yii2. For more information, please follow other related articles on the PHP Chinese website!