yii2:formatting 显示日期

yii2:formatting of date for display

我已将日期字段 appointment_date 配置为 mysql 数据库中的 datetime 字段。

在我的模型中 Appointment.php 规则设置如下:

public function rules()
    {
        return [
            [['appointment_date','weekdays'], 'safe'],
            [['appointment_date'], 'date','format' => 'd-M-yyyy H:m'],

并且在 web.php 组件下我设置了

'formatter' => [
        'defaultTimeZone' => 'UTC',
        'timeZone' => 'Asia/Kolkata',

在我看来,我正在尝试格式化显示日期:

[
    Yii::$app->formatter->asDatetime('appointment_date')
 ],

现在我收到错误 -

appointment_date' is not a valid date time value: DateTime::__construct(): Failed to parse time string (appointment_date) at position 0 (a): The timezone could not be found in the database
Array
(
[warning_count] => 1
[warnings] => Array
(
[6] => Double timezone specification
)

[error_count] => 3
[errors] => Array
(
[0] => The timezone could not be found in the database
[11] => Unexpected character
[12] => Double timezone specification
)

而数据库中存储的日期如下:2015-01-20 11:50:00

如果我没有格式化日期,只是将属性保持在视图中 appointment_date 那么日期显示为 2015-01-20 11:50:00

我想将日期显示为 20-01-2015 11:50:00

如果我使用这样的代码:

[
    'attribute'=>'appointment_date',
     'format'=>['DateTime','php:d-m-Y H:i:s']
            ],

我得到的日期格式正确。

我想知道我在使用

时做错了什么
Yii::$app->formatter->asDatetime('appointment_date')

谢谢

我认为这只是一个小错别字。您将一个字符串传递给 asDateTime 方法,它需要值

Yii::$app->formatter->asDatetime('appointment_date')

应该是

Yii::$app->formatter->asDatetime($model->appointment_date)

文档:http://www.yiiframework.com/doc-2.0/yii-i18n-formatter.html#asDatetime()-detail

OK就这么简单,我需要用

'appoinment_date:date'

'appointment_date:datetime'

并在组件格式化程序中添加格式

'formatter' => [
       'defaultTimeZone' => 'UTC',
       'timeZone' => 'Asia/Kolkata',
       'dateFormat' => 'php:d-m-Y',
       'datetimeFormat'=>'php:d-M-Y H:i:s'

现在一切正常。

我的数据库日期类型是 date,因此它以 "YYYY-DD-MM" 格式存储和给出响应。
我在视图 (index.php) 中这样做,没有更改逻辑或数据库数据。

最初是

'date' 

我用这个改变了-

            [
                'attribute' => 'date',
                'value' => function ($model, $key, $index, $widget) { 
                    return date("d-m-Y", strtotime($model->date));
                },
            ],

它对我来说很好用,
希望它能为更多有需要的人工作。

将以下代码放在 Project/config/web 中的组件部分下。php

'formatter' => [
   'defaultTimeZone' => 'UTC',
   'timeZone' => 'Asia/Kolkata',
   'dateFormat' => 'php:d-m-Y',
   'datetimeFormat'=>'php:d-M-Y H:i:s'
   ]

在网格中显示日期或日期时间的地方只需添加此 对于日期

'date_column_name:date'

对于日期时间

'datetime_column_name:datetime'

这 it.It 将适用于您想要更改日期或日期时间格式的整个项目。