Reputation: 7451
I have an API built with Symfony2 and Doctrine.
Dates are stored in the database without timezone modifiers (e.g. +0000
).
However, Doctrine's ->findAll()
method returns the dates with a timezone modifier attached. How do I ensure this does not happen? Adding this to entity annotations? Or maybe creating an event listener to modify the data (seems like it might get a bit messy to me though), or is there another way that this should be done?
Thanks
Upvotes: 0
Views: 130
Reputation: 7451
I forgot to mention I was using FOSRestBundle, so needed to add this to entities in the end:
use JMS\Serializer\Annotation\Type;
...
@Type("DateTime<'Y-m-d'>")
Thanks to this for help: Format returning date format on Symfony2 FOSRestBundle
Upvotes: 0
Reputation: 12740
Sticking ->format('Y-m-d H:i:s');
for return value is the cleanest and simplest solution to me.
class MyEntity
{
protected $dateOfBirth;
public function setDateOfBirth(DateTime $dateOfBirth)
{
$this->dateOfBirth = $dateOfBirth;
return $this;
}
public function getDateOfBirth()
{
return $this->dateOfBirth->format('Y-m-d H:i:s');
}
}
Upvotes: 1
Reputation: 5767
Doctrine hydrates the date
and datetime
columns as standard php DateTime
objects.
According to http://php.net/manual/en/datetime.construct.php:
If $timezone is omitted, the current timezone will be used.
This means that even if doctrine doesn't set the timezone when hydrating the object the system's default timezone will be used. This is standard php behavior and it can't be changed from Doctrine.
Solution:
Even if the dates are constructed with a a timezone, this shouldn't bother you much. Using DateTime
's format()
method you can display the date in any format you want.
Example:
To display the date in a 2000-02-01 23:59:59
format you can do:
$entities = $repository->findAll();
foreach($entities as $entity){
echo $entity->mydate->format('Y-m-d H:i:s');
}
Upvotes: 1