All posts
Engineering 1 min read

Configure default datetime format of Symfony Serializer DateTimeNormalizer

I know that’s a mouthful of a title but it has just taken me forever to find out how to do this and hopefully this title will help some people to not run down the same rabbit holes.

By default the Symfony Serializer Component uses the built in DateTimeNormalizer. That will take a DateTime object (or anything that implements the interface, such as datetimeimmutable) and normalize it into a string. The default is given as DateTimeInterface::RFC3339 which produces output like 2005-08-15T15:52:01+00:00 for the normalized value. That is fine for most people but I needed a bit extra. Although the official RFC3339 supports milliseconds at least, in PHP it’s hidden behind the DateTimeInterface::RFC3339_EXTENDED constant, which then produces 2005-08-15T15:52:01.000+00:00 as an output. What if you want that or even go down to microseconds (6 decimals)? A lot of nothing is to be found everywhere on that topic. So I came up with my own.

Simply put, you just overwrite the default normalizers service definition with your own. This is from a Symfony 5.0.1 application and it’s in the root directory services.yaml file on the config folder. Order of loading things matters, so if it doesn’t work for you, you might need to check when it’s getting loaded.

services:    serializer.normalizer.datetime:        class: ‘Symfony\Component\Serializer\Normalizer\DateTimeNormalizer        arguments            -                !php/const Symfony\Component\Serializer\Normalizer\DateTimeNormalizer::FORMAT_KEY: ‘Y-m-d\TH:i:s.uP’        tags:            - { name: serializer.normalizer, priority: -910 }

And that’s it. The ‘Y-m-d\TH:i:s.uP’ part is what you need to replace with your own pattern to have what you need. This will operate on every single date time though now, so if you need a more finegrained control on a per property basis, this will probably not be for you.