2015-01-20 85 views
5

我已经在mysql db中将日期字段appointment_date配置为datetime字段。yii2:显示日期的格式

在我的模型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年1月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') 

感谢

回答

6

我认为这只是一个小错字什么。你传递一个字符串到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

+0

@ fl0r-你的建议也是正确的,但我需要使用像'attribute =>'appointment_date','value'=> Yii :: $ app-> formatter-> asDatetime($ model-> appointment_date ) – Pawan 2015-01-21 13:26:17

6

确定它是如此简单,我需要使用

'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' 

添加的格式,现在是工作的罚款。

0

我的数据库日期类型是date因此它正在存储并给出响应“YYYY-DD-MM”成员。
我在视图(index.php)中没有更改逻辑或DB数据。

的初衷是

'date' 

我与这个 -

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

改变人们对我工作的罚款,
希望它会为一些更有需要的工作。

0

把下面的代码下的项目的组件部分/配置/ web.php

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

你在哪里显示datetimein网格日期OT只需添加这 对于日期

'date_column_name:date' 

对于日期时间

'datetime_column_name:datetime' 

就是这样,它会为您的整个项目工作,哟你想改变日期或日期时间格式。