Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
229 views
in Technique[技术] by (71.8m points)

php - Symfony buildForm convert datetime to local and back to utc

So I want to show options to set a date for an activity in local time but save it in UTC as symfony standard. I have 5 different User segments with 5 different Timezones values. A user can set a new activity in a form. Each user entity has it's own timezone set. My question is where do I set the conversion? I have the user entity in a logged in user session state.

In the ControllerAction where I invoke the formBuilder?

In the formBuilder?

The formbuilder is still a little fuzzy for me and I know there's alot happening in it.

The formBuilder, simplified:

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')));
}

The 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);
}

So I believe, I've just answered my own question, which forces me to ask; Is this the convention/best practice how you do it?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You're overcomplicating this. Symfony2 forms already covers this nicely.

Please see:

Model timezone: http://symfony.com/doc/current/reference/forms/types/date.html#model-timezone

View timezone: http://symfony.com/doc/current/reference/forms/types/date.html#view-timezone

Used correctly these solve your issue without any extra code needed.

You could inject your user segment (or whatever data you use to deduce which is the correct time zone) into your form and use the timezone on that user segment to set view_timezone on your date field. Something along those lines anyway :)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...