Symfony 4 - Set DateTime

treyBake picture treyBake · May 22, 2018 · Viewed 24.3k times · Source

so I've been following this Database and the Doctrine tutorial: https://symfony.com/doc/current/doctrine.html

the only difference is that I added a created_ts field to it (among some other fields, but they work fine so no need to go into them).

I used the make:entity command to generate my class and the method for setting my created_ts got generated like this:

public function setCreatedTs(\DateTimeInterface $created_ts): self
{
    $this->created_ts = $created_ts;

    return $this;
}

So in my /index page I went to save a new entity using:

$category->setCreatedTs(\DateTimeInterface::class, $date);

I had a funny feeling this would error and I was right:

Type error: Argument 1 passed to App\Entity\Category::setCreatedTs() must implement interface DateTimeInterface, string given

but I'm not sure how to implement the DateTimeInterface inside the function.. I tried googling but it shows a lot of Symfony2 posts, a few I tried to no avail.

How do I set a datetime value in my entity from the ->set method?

(if there is already an answer, please link. #symfonyScrub)

update

# tried doing this:
$dateImmutable = \DateTime::createFromFormat('Y-m-d H:i:s', strtotime('now')); # also tried using \DateTimeImmutable

$category->setCategoryName('PHP');
$category->setCategoryBio('This is a category for PHP');
$category->setApproved(1);
$category->setGuruId(1);
$category->setCreatedTs($dateImmutable); # changes error from about a string to bool

Answer

fxbt picture fxbt · May 22, 2018

If your date is the current date, you can just do this:

$category->setCreatedTs(new \DateTime())

Your first error was caused by the strtotime function that returns a timestamp but the \DateTime constructor was expecting a Y-m-d H:i:s format.

That's why instead of creating a valid \DateTime, it returned false.

Even if it's unnecessary in this case, you should have done something like this to create a \DateTime based on a timestamp:

$date = new \DateTime('@'.strtotime('now'));