2017-08-19 116 views
0

使用yii2的格式化程序(請參見下文)很容易將UTC(數據庫)時間轉換爲用戶時區,但是,如何將用戶時區轉換回數據庫時區?yii2將用戶時區轉換爲數據庫時區以便保存

我的配置文件如下:

.... 
'formatter' => [ 
    'class' => 'yii\i18n\Formatter', 
    'defaultTimeZone'=>'UTC',// for saving values in the database    
    'timeZone'=>'America\New_York', // for displaying timezones 
],.... 

要顯示用戶本地時區,很容易只要致電:

echo Yii::$app->formatter->asDatetime($model->date_created); 

你怎麼轉換回去,這樣,當他們提交值,我可以將其轉換回UTC格式?

+0

你需要更具體地說明你想要保存什麼以及如何保存。 – Bizley

+0

猜你可以設置'\ Yii :: $ app-> formatter-> timeZone ='UTC';'當你需要(假設輸入包含時區信息)......但是,我不認爲格式化程序真的是用於這種用途。您可能需要考慮使用[DateTime](http://php.net/manual/en/class.datetime.php),您可以使用用戶的時間數據和時區進行初始化,然後根據您的喜好在時區和格式之間進行轉換,或者只要使用UNIX時間戳(如果存儲在數據庫中)。 – Thernys

回答

0

正如Thernys建議,用戶提交他們的本地時區,它被轉換模型如下:

protected function convertToServerDate($date, $format = 'n/j/Y g:i A', 
    $userTimeZone = 'America/Los_Angeles', $serverTimeZone = 'UTC') 
    { 
    try { 
     $dateTime = new DateTime ($date, new DateTimeZone($userTimeZone)); 
     $dateTime->setTimezone(new DateTimeZone($serverTimeZone)); 
     return $dateTime->format($format); 
    } catch (Exception $e) { 
     return ''; 
    } 
    } 

,然後在我的模型驗證規則做到這一點:

public function rules(){ 
    return [ 
    ..... 
    [['datetimeattribute'],'filter','filter'=>function($value){ 
    return $this->convertToServerDate($value,'Y-m-d H:i:s',Yii::$app->formatter->timeZone,Yii::$app->formatter->defaultTimeZone) 
    }] 
..... 
];