简体   繁体   中英

Enabling microseconds in Symfony2 (Doctrine) and MySQL

I have an entity with one column of "datetime" type to store a timestamp.

 /** * @ORM\\Column(type="datetime") */ protected $timestamp;

I had MySQL 5.5.40 and I discovered it does not store microseconds. So I switched to 5.6.21 and imported all my tables and data.

I tried to declare the type as

 * @ORM\\Column(type="datetime(6)")

but it gave me an error. So I changed it directly in the DB by doing:

 ALTER TABLE symfony.hrmgmt MODIFY timestamp DATETIME(6);

In my controller I do this:

 $dt = new \\DateTime('now'); $newHREvent->setTimestamp($dt);

But nonetheless the timestamp is stored without fractions of second.

I can (now) manually enter datetime with fractional values via SQL, but when I do it through my controller it always stores with .000000

I suppose that's because Doctrine does not know that it can store also microseconds.

My PHP version is still 5.4.34.

Thank you!

要使用微秒创建日期时间,您必须在控制器中使用DateTime::createFromFormat

$date = \DateTime::createFromFormat('U.u', (string)microtime(true));

tl;dr #

Follow this blog, create your own custom data type and use it https://blog.tomhanderson.com/2018/09/datetime-with-microseconds-for-mysql-in.html

For the patient and curios ones

I am coming here after having gone through the exact steps that you mentioned, upgrading mysql, changing column datatype precision manually, and I was at the exact state as you are...

This is not got to do with PHP version, but instead Doctrine has a role to play here.

Just like for decimal values doctrine supports precision and scale type="decimal" Ex: precision=10, scale=2 , it should have supported for datetime , however it doesn't at the moment

The issue is currently being tracking here https://github.com/doctrine/dbal/issues/2873

However, there is a blog that explains a workaround until doctrine fixes this at their end https://blog.tomhanderson.com/2018/09/datetime-with-microseconds-for-mysql-in.html

I believe it was written by Tom H Anderson

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM