一个稳健的解决方案是实现您自己的 DBAL 类型,使用实现了 __toString() 的 DateTime 后代:
<?php
class DateKey extends \DateTime{
function __toString() {
return $this->format('c');
}
static function fromDateTime(\DateTime $dateTime) {
return new static($dateTime->format('c'));
}
}
class DateKeyType extends \Doctrine\DBAL\Types\DateType{
public function convertToPHPValue($value, \Doctrine\DBAL\Platforms\AbstractPlatform $platform) {
$value = parent::convertToPHPValue($value, $platform);
if ($value !== NULL) {
$value = DateKey::fromDateTime($value);
}
return $value;
}
public function getName()
{
return 'DateKey';
}
}
\Doctrine\DBAL\Types\Type::addType('datekey', 'DateKeyType');
//edit: do not forget this after creating entity manager.
//otherwise, you will get into problems with doctrine database diff / migrations.
$platform = $entityManager->getConnection()->getDatabasePlatform();
$platform->registerDoctrineTypeMapping('datekey', 'datekey');
$platform->markDoctrineTypeCommented(\Doctrine\DBAL\Types\Type::getType('datekey'));