[Serializer] fixed DateTimeNormalizer to maintain microseconds when a different timezone required

This commit is contained in:
Vitaliy Ryaboy 2018-12-01 19:23:29 +01:00 committed by Nicolas Grekas
parent 51d78b5eca
commit 2bf8a1cae6
2 changed files with 78 additions and 1 deletions

View File

@ -59,7 +59,8 @@ class DateTimeNormalizer implements NormalizerInterface, DenormalizerInterface
$timezone = $this->getTimezone($context);
if (null !== $timezone) {
$object = (new \DateTimeImmutable('@'.$object->getTimestamp()))->setTimezone($timezone);
$object = clone $object;
$object = $object->setTimezone($timezone);
}
return $object->format($format);

View File

@ -78,6 +78,82 @@ class DateTimeNormalizerTest extends TestCase
yield array('2016-12-01T09:00:00+09:00', new \DateTimeImmutable('2016/12/01', new \DateTimeZone('UTC')), new \DateTimeZone('Japan'));
}
/**
* @dataProvider normalizeUsingTimeZonePassedInContextAndExpectedFormatWithMicrosecondsProvider
*/
public function testNormalizeUsingTimeZonePassedInContextAndFormattedWithMicroseconds($expected, $expectedFormat, $input, $timezone)
{
$this->assertSame(
$expected,
$this->normalizer->normalize(
$input,
null,
array(
DateTimeNormalizer::TIMEZONE_KEY => $timezone,
DateTimeNormalizer::FORMAT_KEY => $expectedFormat,
)
)
);
}
public function normalizeUsingTimeZonePassedInContextAndExpectedFormatWithMicrosecondsProvider()
{
yield array(
'2018-12-01T18:03:06.067634',
'Y-m-d\TH:i:s.u',
\DateTime::createFromFormat(
'Y-m-d\TH:i:s.u',
'2018-12-01T18:03:06.067634',
new \DateTimeZone('UTC')
),
null,
);
yield array(
'2018-12-01T18:03:06.067634',
'Y-m-d\TH:i:s.u',
\DateTime::createFromFormat(
'Y-m-d\TH:i:s.u',
'2018-12-01T18:03:06.067634',
new \DateTimeZone('UTC')
),
new \DateTimeZone('UTC'),
);
yield array(
'2018-12-01T19:03:06.067634+01:00',
'Y-m-d\TH:i:s.uP',
\DateTimeImmutable::createFromFormat(
'Y-m-d\TH:i:s.u',
'2018-12-01T18:03:06.067634',
new \DateTimeZone('UTC')
),
new \DateTimeZone('Europe/Rome'),
);
yield array(
'2018-12-01T20:03:06.067634+02:00',
'Y-m-d\TH:i:s.uP',
\DateTime::createFromFormat(
'Y-m-d\TH:i:s.u',
'2018-12-01T18:03:06.067634',
new \DateTimeZone('UTC')
),
new \DateTimeZone('Europe/Kiev'),
);
yield array(
'2018-12-01T21:03:06.067634',
'Y-m-d\TH:i:s.u',
\DateTime::createFromFormat(
'Y-m-d\TH:i:s.u',
'2018-12-01T18:03:06.067634',
new \DateTimeZone('UTC')
),
new \DateTimeZone('Europe/Moscow'),
);
}
/**
* @expectedException \Symfony\Component\Serializer\Exception\InvalidArgumentException
* @expectedExceptionMessage The object must implement the "\DateTimeInterface".