Symfony to set a DateTime in MySQL database

2019-08-03 10:46发布

Question:

In a DB web app, Date/Time field is very common.

When in Symfony, you tried to do either of the follwings:

$creationDate=new DateTime();
$record->setCreationDate($creattionDate);

This will create a "Object DateTime can't be converted to string" error.

Or:

$creationDate=new DateTime();
$datestr=$creationDate->format('Y-m-d H:i:s');
$record->setCreationDate($datestr);

This will create "Calling method format() on a non-ojbect" error.

2条回答
欢心
2楼-- · 2019-08-03 11:18

Solution:

Hack the DateTimeType.php located at: your symfony root/vendor/doctrine/dbal/lib/Doctrine/DBAL/Types/DateTimeType.php for the function named convertToDatabaseValue

Original content:

return ($value !== null)
    ? $value->format($platform->getDateTimeFormatString()) : null;

It seems Symfony is doing some extra conversion when the parameter is already a string.

Change to:

 return ($value !== null)
            ? $value : null;

will do the trick.

查看更多
\"骚年 ilove
3楼-- · 2019-08-03 11:26

In your entity you have to map your field with date or datetime type.

@ORM\Column(name="creationDate", type="date", nullable=true)

查看更多
登录 后发表回答