Symfony News

New in Symfony 3.1: DateTime Normalizer

Kévin Dunglas

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,
    [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"
// }

Be trained by Symfony experts - 2016-04-22 Clichy - 2016-04-26 London - 2016-04-26 London


About us

What a Symfony developer should know about the framework: News, Jobs, Tweets, Events, Videos,...

Resources

Find us on Twitter

Find us on Facebook