Search code examples
phpmysqldatetimedoctrinesymfony3.x

How do I properly store a datetime in Symfony 3?


I'm trying to store a mysql datetime in a Symfony repo and am getting an error. Tried several suggestions from the web and here on stack but nothing makes this error go away. This is what I'm trying to do (code is abbreviated for clarity)

My entity field:

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

My repo code:

$reservedays = 84;
$now = new \DateTime('NOW');
$now->modify('+' . $reservedays .' days');
$payment = new AppBundle\Entity\Payment;
$payment->setCreated( $now->format('Y-m-d h:i:s') );

But I am consistently getting this error:

Error: Call to a member function format() on string
500 Internal Server Error - FatalErrorException 

Stack Trace:
1. in vendor/doctrine/dbal/lib/Doctrine/DBAL/Types/DateTimeType.php at line 53  -

    public function convertToDatabaseValue($value, AbstractPlatform $platform)
    {
        return ($value !== null)
            ? $value->format($platform->getDateTimeFormatString()) : null;
    }
    /**

As you can see I want to take the current date and add 84 days to it and then store it into a mysql datetime but no matter what I've tried this error keeps coming up. Anyone?


Solution

  • It's not necessary to use 'NOW' when creating new DateTime object. You can simply use $now = new \DateTime() for actual date/time.

    To your case - it's completely o.k. to create DateTime object, modify it by adding XYdays, so:

    $reservedays = 84;
    $now = new \DateTime();
    $now->modify('+' . $reservedays .' days');
    

    But then you should to use DateTime object as a setCreated() method param, because the $created property has \DateTime type. The Doctrine layer in Symfony takes care of proper persisting data to the DB, so this should work fine:

    $payment = new AppBundle\Entity\Payment;
    $payment->setCreated($now);