Symfony 4 - 设置日期时间

Symfony 4 - Set DateTime

所以我一直在关注这个数据库和 Doctrine 教程:https://symfony.com/doc/current/doctrine.html

唯一的区别是我在其中添加了一个 created_ts 字段(在其他一些字段中,但它们工作正常,因此无需进入)。

我使用 make:entity 命令生成我的 class 并且设置我的 created_ts 的方法是这样生成的:

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

    return $this;
}

所以在我的 /index 页面中,我使用以下方法保存了一个新实体:

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

我有一种奇怪的感觉,这会出错,我是对的:

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

但我不确定如何在函数内部实现 DateTimeInterface。我尝试使用谷歌搜索,但它显示了很多 Symfony2 帖子,其中一些我尝试无济于事。

如何通过 ->set 方法在我的实体中设置 datetime 值?

(如果已经有答案,请link。#symfonyScrub)

更新

# 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

如果你的日期是当前日期,你可以这样做:

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

您的第一个错误是由 strtotime 函数引起的 returns 时间戳,但 \DateTime 构造函数期望 Y-m-d H:i:s 格式。

这就是为什么它没有创建有效的 \DateTime,而是返回 false。

即使在这种情况下没有必要,您也应该像这样根据时间戳创建 \DateTime

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