代码之家  ›  专栏  ›  技术社区  ›  treyBake user1850175

symfony 4-设置日期时间

  •  5
  • treyBake user1850175  · 技术社区  · 7 年前

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

    唯一的区别是我加了一个 created_ts 它的领域(在一些其他领域,但他们工作得很好,所以不需要进入他们)。

    我用了 make:entity 生成类的命令和设置 已创建 生成如下:

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

    所以在我的 /index 第i页使用以下方法保存新实体:

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

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

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

    但我不知道如何实现 DateTimeInterface 在函数内部..我试过谷歌搜索,但它显示了很多 Symfony2 博文,几篇我都试着没用。

    我怎么设置A datetime 我的实体中的值来自 ->set 方法?

    (如果已经有答案,请链接。#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
    
    1 回复  |  直到 7 年前
        1
  •  13
  •   fxbt    7 年前

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

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

    您的第一个错误是由 strtotime 返回时间戳的函数,但\datetime构造函数需要 Y-m-d H:i:s 格式。

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

    即使在这种情况下这是不必要的,您也应该这样做来创建一个 \DateTime 基于时间戳:

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