Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symfony serialization: changing default DateTimeNormalizer format

I am trying to serialize an entity class which has some \DateTime fields. Everything works fine, but \DateTime objects are converted to string using the following format: "2019-10-21T01:05:12+00:00", while I would like to get just the date part: "2019-10-21".

Symfony documentation mentions default format but doesn't explain how to configure it:

DateTimeNormalizer This normalizer converts DateTimeInterface objects (e.g. DateTime and DateTimeImmutable) into strings. By default, it uses the RFC3339 format.

Is it possible to change the default DateTime normalization format and how?

Entity class:

class Fact
{
    /**
     * @ORM\Column(type="datetime", options={"default": "CURRENT_TIMESTAMP"})
     * @Groups({"api"})
     */
    private $created_on;
}

Normalization example:

use Symfony\Component\Serializer\SerializerInterface;

class FactController extends AbstractController
{
    private $serializer;

    public function __construct(SerializerInterface $serializer)
    {
        $this->serializer = $serializer;
    }

    public function view($id)
    {
        ....   
        $data = array(
            'fact' => $this->serializer->normalize($fact, null, ['groups'=> 'api']),
        );
        ...
    }
}
like image 293
kutas Avatar asked Oct 19 '25 01:10

kutas


2 Answers

It turns out that '$context' array is passed down to normalize() function of each supported Normalizer. Built-in Normalizers define array keys they accept and their default values.

The relevant key in my case is 'datetime_format', which defaults to \DateTime::RFC3339. Format must be the one accepted by \DateTime::format() and \DateTime::createFromFormat() methods - these functions are used for normalization / denormalization.

Correct usage in my case is:

    public function view($id)
    {
        ....   
        $data = array(
            'fact' => $this->serializer->normalize($fact, null, ['groups'=> 'api',
                                                                 'datetime_format' => 'Y-m-d']),
        );
        ...
    }
like image 61
kutas Avatar answered Oct 21 '25 17:10

kutas


Here is an answer in another question. Solution is:

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 }

Priority is taken from the original service, so, this solution will not have any side effects.

like image 24
Oleksandr Savchenko Avatar answered Oct 21 '25 16:10

Oleksandr Savchenko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!