How to create DateTime object from string in symfony2/php
datetime, php, symfony
Solution
I always create a `DateTime` object with its constructor, in your case it would be:
$protocol->setStartedAt(new \DateTime($post['started_at']));
if this works but does not use the timestamp posted you probably do not have the value in `$post['started_at']`. Try debugging it or just do the dirty trick:
die($post['started_at']);
Problem
In a DB table I have several fields with `datetime` as field type. So I need to persist data only as date time object. From a form I get date time as string like ``` 2012-10-05 17:45:54 ``` Now when ever I persist my entity I get following error: Fatal error: Call to a member function format() on a non-object in ..\DateTimeType.php on line 44 I tried with ``` $protocol->setStartedAt(strtotime($post['started_at'])); ``` or ``` $from = \DateTime::createFromFormat('yy-mm-dd hh:mm:ss', $post['started_at']); $protocol->setStartedAt($from); ``` or just ``` $from = new \DateTime($post['started_at']); $protocol->setStartedAt($from); ``` The last code works but it does not uses the timestamp passed as arguement but just gets the current time. Any ideas?