2015-01-20 80 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' 

就是這樣,它會爲您的整個項目工作,喲你想改變日期或日期時間格式。