Define Date and Time Format for Serialization in Symfony 7

Define Date and Time Format for Serialization in Symfony 7

The Serializer component supports DateTimeNormalizer that allows to convert DateTimeInterface objects (e.g. DateTime) into date and time format string. By default, RFC3339 format is used.

This tutorial shows how to define date and time format for serialization in Symfony 7 application.

Let's say we have the following class:



namespace App\Entity;

use DateTime;

class Notification
    private DateTime $sentAt;

    public function getSentAt(): DateTime { return $this->sentAt; }
    public function setSentAt(DateTime $sentAt): void { $this->sentAt = $sentAt; }

The Serializer component allows specifying date and time format using DateTimeNormalizer::FORMAT_KEY option.



namespace App\Controller;

use App\Entity\Notification;
use DateTime;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;
use Symfony\Component\Serializer\Encoder\JsonEncoder;
use Symfony\Component\Serializer\Normalizer\DateTimeNormalizer;
use Symfony\Component\Serializer\SerializerInterface;

class TestController
    public function index(SerializerInterface $serializer): Response
        $notification = new Notification();
        $notification->setSentAt(new DateTime('2022-02-27 07:50:00'));

        $json = $serializer->serialize(
            [DateTimeNormalizer::FORMAT_KEY => 'Y-m-d H:i:s']

        return new Response($json); // Output: {"sentAt":"2022-02-27 07:50:00"}

Leave a Comment

Cancel reply

Your email address will not be published.