New in Symfony 3.1: DateTime Normalizer

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 normalizes DateTime 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
use Symfony\Component\Serializer\Normalizer\DateTimeNormalizer;
use Symfony\Component\Serializer\Serializer;

$serializer = new Serializer(array(new DateTimeNormalizer()));

$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 the DateTimeNormalizer constructor:

1
2
3
4
5
// ...
$serializer = new Serializer(array(new DateTimeNormalizer('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 = new Serializer(array(new DateTimeNormalizer()));

$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 = new Serializer(array(new DateTimeNormalizer()));

$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"
// }

Comments

Comments are closed.

To ensure that comments stay relevant, they are closed for old posts.