Reputation: 301
In my entity, i have two fields, one type DateTime and other type Time.
I'm trying to do this:
$time = "05:45";
$date = "01-09-2015"
$entity = new Entity();
$entity->setDate(new \DateTime($date));
$entity->setTime($time);
In both case, Symfony told me that the code has problems with format.
I also tried:
->setDate(new Datetime($date));
->setDate(DateTime::createFromFormat($date, 'd-m-Y));
->setTime(strtotime($time));
Always with the same result.
If anybody could help me, i'll be thankful.
Thanks
UPDATED
Now, I tried
$date = strtotime($date);
$time = strtotime($time);
$entity->setDate(date("d-m-Y", $date));
$entity->setTime(date("H:i",$time));
And Symfony told me:
Error: Call to a member function format() on a non-object
in vendor/doctrine/dbal/lib/Doctrine/DBAL/Types/TimeType.php at line 53 -
public function convertToDatabaseValue($value, AbstractPlatform $platform)
{
return ($value !== null)
? $value->format($platform->getTimeFormatString()) : null;
}
/**
I also tried this:
$dateObject = new DateTime();
$date = $dateObject->format('d-m-Y');
$time = $dateObject->format('H:i');
$entity->setDate($date);
$entity->setTime($time);
And symfony told me:
Attempted to call method "format" on class "Symfony\Component\Validator\Constraints\DateTime". On line "$date = $dateObject->format('Y-m-d');"
Thanks for the help
Updated - Resolve
Finally, yesterday a resolved the problem, using this:
$entity->new Entity();
$entity->setDate(\DateTime::createFromFormat('d-m-Y',$date));
$entity->setTime(\DateTime::createFromFormat('H:i',$time));
Thanks!
Upvotes: 5
Views: 20924
Reputation: 1280
Symfony doesn't know where to find DateTime
class, so it is searching in the wrong (default) namespace. Use a leading \
.
Moreover you inverted the format
argument and the time
argument in the createFromFormat()
function.
So your code becomes:
$time = "05:45";
$date = "01-09-2015"
$entity = new Entity();
$entity->setDate(\DateTime::createFromFormat('d-m-Y', $date));
$entity->setTime(\DateTime::createFromFormat('H:i', $time));
By the way, are you sure you really need to split Date and Time in your entity? It depends on your case but you could do this instead (only one object to manipulate):
$time = "05:45";
$date = "01-09-2015"
$entity = new Entity();
$entity->setDateTime(\DateTime::createFromFormat('d-m-Y H:i', $date.' '.$time));
Upvotes: 8
Reputation: 307
Do it like this:
$dateObject = new DateTime();
$date = $dateObject->format('Y-m-d');
$time = $dateObject->format('H:i:s'); // or $time = $dateObject->format('H:i'); if you dont want to have the seconds
$entity = new Entity();
$entity->setDate($date);
$entity->setTime($time);
Upvotes: 1
Reputation: 4089
Check out http://php.net/manual/de/datetime.createfromformat.php to be sure that your format fits.
Or check mktime(hour,minute,second,month,day,year) Or check strtotime(time,now) e.g. here http://www.w3schools.com/php/php_date.asp
Upvotes: 1