yii2将用户时区转换为数据库时区以便保存

问题描述:

使用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

正如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) 
    }] 
..... 
];