Lukas Klizas
Lukas Klizas

Reputation: 175

Symfony2 entity Time type return format

I have entity for saving place's working time:

<?php

namespace AppBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * WorkingTime
 *
 * @ORM\Table(name="working_time")
 *     @ORM\Entity(repositoryClass="AppBundle\Repository\WorkingTimeRepository")
 */
class WorkingTime
{
/**
 * @var int
 *
 * @ORM\Column(name="id", type="integer")
 * @ORM\Id
 * @ORM\GeneratedValue(strategy="AUTO")
 */
private $id;

/**
 * @var int
 *
 * @ORM\Column(name="day", type="smallint")
 */
private $day;

/**
 * @var \DateTime
 *
 * @ORM\Column(name="start", type="time")
 */
private $start;

/**
 * @var \DateTime
 *
 * @ORM\Column(name="end", type="time")
 */
private $end;


/**
 * Get id
 *
 * @return integer
 */
public function getId()
{
    return $this->id;
}

/**
 * Set day
 *
 * @param integer $day
 *
 * @return WorkingTime
 */
public function setDay($day)
{
    $this->day = $day;

    return $this;
}

/**
 * Get day
 *
 * @return integer
 */
public function getDay()
{
    return $this->day;
}

/**
 * Set start
 *
 * @param \DateTime $start
 *
 * @return WorkingTime
 */
public function setStart($start)
{
    $this->start = $start;

    return $this;
}

/**
 * Get start
 *
 * @return \DateTime
 */
public function getStart()
{
    return $this->start;
}

/**
 * Set end
 *
 * @param \DateTime $end
 *
 * @return WorkingTime
 */
public function setEnd($end)
{
    $this->end = $end;

    return $this;
}

/**
 * Get end
 *
 * @return \DateTime
 */
public function getEnd()
{
    return $this->end;
}
}

But when I try to display retrieve it, time fields are converted to something like:

 {
          "id": 16,
          "day": 2,
          "start": "1970-01-01T07:00:00+0000",
          "end": "1970-01-01T00:00:00+0000"
  },

Is it possible, that it gets converted by FOSRestBundle? How can I get rid of it and get only HH:mm, instead of 1970-01-01T00:00:00+0000?

Upvotes: 4

Views: 1932

Answers (1)

chalasr
chalasr

Reputation: 13167

The FOSRestBundle serialises objects before render them.

To do this, you need to choose between the built-in Symfony serializer or the JMSSerializer.

As you don't manually use one of them for now, and because it provides a solution for this specific problem, I will give the solution for do it using the JMSSerializer.
To use it, you need only to follow the installation chapter of the documentation.

Then, in your entity, use the @Type annotation on the time properties :

use JMS\Serializer\Annotation as JMS;
// ...

/**
 * @JMS\Type("DateTime<'H:i'>")
 * @ORM\Column(name="start", type="time")
 */
private $start;

/**
 * @JMS\Type("DateTime<'H:i'>")
 * @ORM\Column(name="end", type="time")
 */
private $end;

Now, your properties will be rendered as 07:00 instead of 1970-01-01T07:00:00+0000.

Upvotes: 6

Related Questions