Skip to content

Instantly share code, notes, and snippets.

@coudenysj
Last active February 22, 2016 12:40
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save coudenysj/6dc8ba55c43b97143a6c to your computer and use it in GitHub Desktop.
Save coudenysj/6dc8ba55c43b97143a6c to your computer and use it in GitHub Desktop.
Doctrine DateTimeType supporting MySQL fractional seconds
<?php
// add this line somewhere in the bootstrap
\Doctrine\DBAL\Types\Type::overrideType('datetime', 'My\Project\DBAL\Types\DateTimeType');
<?php
/**
* A custom type type for datetime(3) in MySQL.
*
* @see http://www.doctrine-project.org/jira/browse/DBAL-1084
*/
namespace My\Project\DBAL\Types;
use Doctrine\DBAL\Types\ConversionException;
use Doctrine\DBAL\Platforms\AbstractPlatform;
class DateTimeType extends \Doctrine\DBAL\Types\DateTimeType
{
/**
* {@inheritdoc}
*/
public function convertToDatabaseValue($value, AbstractPlatform $platform)
{
if ($value === null) {
return null;
}
$format = $platform->getDateTimeFormatString();
if ((int) $value->format('u') === 0) {
$format .= '.u';
}
return $value->format($format);
}
/**
* {@inheritdoc}
*/
public function convertToPHPValue($value, AbstractPlatform $platform)
{
if ($value === null || $value instanceof \DateTime) {
return $value;
}
$format = $platform->getDateTimeFormatString();
if (preg_match('/.+\.\d+$/', $value)) {
$format .= '.u';
}
$val = \DateTime::createFromFormat($format, $value);
if (!$val) {
throw ConversionException::conversionFailedFormat($value, $this->getName(), $platform->getDateTimeFormatString() . '.u');
}
return $val;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment