所以我想顯示選項以在當地時間爲活動設置一個日期,但將其另存爲UTC作爲symfony標準。我有5個不同的用戶分段和5個不同的時區值。用戶可以在表單中設置新的活動。每個用戶實體都有自己的時區設置。我的問題是我在哪裏設置轉換?我有用戶實體處於登錄用戶會話狀態。Symfony buildForm將datetime轉換爲本地並返回utc
在我調用formBuilder的ControllerAction中?
在formBuilder中?
formbuilder對我來說還是有些模糊,我知道里面有很多東西在發生。
的formBuilder,簡化:
public function buildForm(FormBuilderInterface $builder, array $options)
{
//...
$builder->add('name');
$builder->add('startDate', DateTimeType::class, array(
'widget' => 'single_text',
'format' => 'yyyy-MM-dd HH:mm',
)
);
$builder->add('endDate', DateTimeType::class, array(
'widget' => 'single_text',
'format' => 'yyyy-MM-dd HH:mm',
)
);
//...
$builder->add('submit', SubmitType::class, array('attr' => array('class' => 'button')));
}
的ControllerAction:
public function activityAction(Request $request, Activity $activity){
$variables = array();
/**
* TODO Determine User Local timezone and store as UTC
*
*/
$user = $this->get('security.token_storage')->getToken()->getUser();
$timezone = $user->getTimezone();
$activity = new Activity();
$form = $this->createForm(ActivityType::class, $activity);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$activity->setName($form->get('name')->getData());
/**
*
* Maybe here, (I've just realized)
* Because earlier, the form just handled the datetime without conversion
* And just stored them in the DB as they where
*
*/
// Example: $timezone = 'Europe/London';
$date = new DateTime();
$date->setTimestamp($form->get('startDate')->getData());
$date->setTimezone(new DateTimeZone($timezone));
$activity->setStartDate($date->format("Y-m-d H:i:s"));
$date = new DateTime();
$date->setTimestamp($form->get('endDate')->getData());
$date->setTimezone(new DateTimeZone($timezone));
$activity->setEndDate($date->format("Y-m-d H:i:s"));
$em = $this->getDoctrine()->getManager();
$em->persist($activity);
$em->flush();
}
elseif ($form->isSubmitted() && !$form->isValid()) {
$variables['message'] = 'Something went wrong!';
}
$variables["title"] = "Create Activty";
$variables["form"] = $form->createView();
return $this->render('AcmeBundle:SomeViews:activity.html.twig', $variables);
}
因此,我相信,我剛纔已經回答我自己的問題,這迫使我問;這是常規/最佳實踐如何做到這一點?
謝謝!我拉着頭髮,直到我注意到我的開發機器在UTC的CEST和生產服務器上。但是這個伎倆! – Conjak