How to set a date in Doctrine 2?

Akrramo picture Akrramo · May 31, 2012 · Viewed 63k times · Source

I have a field named "birthday" in doctrine entity.

I would like to create an object to add to database using doctrine.

Inside the controller :

$name = "John Alex";
$birthday = "11-11-90";
$student = new Student();
$student->setName($name);
$student->setBirthday(strtotime($birthday);
...

but when I try to persist I get this error

Fatal error: Call to a member function format() on a non-object in /Library/WebServer/Documents/Symfony/vendor/doctrine-dbal/lib/Doctrine/DBAL/Types/DateType.php on line 44

Edit:

My entity:

/**
 * @var string $name
 *
 * @ORM\Column(name="name", type="string", length=255)
 */
private $name;

/**
 * @var date $birthday
 *
 * @ORM\Column(name="birthday", type="date", nullable=true)
 */
private $birthday;

/**
 * Set birthday
 *
 * @param date $birthday
 */
public function setBirthday($birthday)
{
    $this->birthday = $birthday;
}

/**
 * Get birthday
 *
 * @return date 
 */
public function getBirthday()
{
    return $this->birthday;
}

Answer

Akrramo picture Akrramo · May 31, 2012
$name = "John Alex";
$birthday = "11-11-1990"; // I changed this
$student = new Student();
$student->setName($name);
$student->setBirthday(new \DateTime($birthday)); // setting a new date instance
// ...