Contributed by
Kévin Dunglas
in #17411.
The Serializer component is one of the most improved components in Symfony 3.1.
This article introduces the new DateTimeNormalizer
which normalizesDateTime
objects into strings and denormalizes them back to objects.
The basic use case to normalize/denormalize dates looks as follows:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | useSymfony\Component\Serializer\Normalizer\DateTimeNormalizer;useSymfony\Component\Serializer\Serializer;$serializer=newSerializer(array(newDateTimeNormalizer()));$dateAsString=$serializer->normalize(new\DateTime('2016/01/01'));// $dateAsString = '2016-01-01T00:00:00+00:00';$dateAsObject=$serializer->denormalize('2016-01-01T00:00:00+00:00',\DateTime::class));// $dateAsObject = class DateTime#1 (3) {// public $date =>// string(26) "2016-01-01 00:00:00.000000"// public $timezone_type =>// int(1)// public $timezone =>// string(6) "+00:00"// } |
If the format is not specified, dates are normalized according to the RFC3339
(using the \DateTime::RFC3339
constant). If you prefer to use another format
to all the normalized dates, pass the new format as the argument of theDateTimeNormalizer
constructor:
1 2 3 4 5 | // ...$serializer=newSerializer(array(newDateTimeNormalizer('Y')));$dateAsString=$serializer->normalize(new\DateTime('2016/01/01'));// $dateAsString = '2016'; |
You can also format each date differently passing the custom format in the context
information provided to the normalize()
method:
1 2 3 4 5 6 7 8 9 | // ...$serializer=newSerializer(array(newDateTimeNormalizer()));$dateAsString=$serializer->normalize(new\DateTime('2016/01/01'),null,array(DateTimeNormalizer::FORMAT_KEY=>'Y/m'));// $dateAsString = '2016/01'; |
The examples shown in this article use DateTime
objects to store dates, but
the new normalizer works for any object implementing the DateTimeInterface
,
such as the DateTimeImmutable
class:
1 2 3 4 5 6 7 8 9 10 11 12 | // ...$serializer=newSerializer(array(newDateTimeNormalizer()));$dateAsObject=$serializer->denormalize('2016-01-01T00:00:00+00:00',\DateTimeInterface::class));// $dateAsObject = class DateTimeImmutable#1 (3) {// public $date =>// string(26) "2016-01-01 00:00:00.000000"// public $timezone_type =>// int(1)// public $timezone =>// string(6) "+00:00"// } |